android中volley的应用

        Volley可说是把AsyncHttpClient和Universal-Image-Loader的优点集于了一身,既可以像AsyncHttpClient一样非常简单地进行HTTP通信,也可以像Universal-Image-Loader一样轻松加载网络上的图片。除了简单易用之外,Volley在性能方面也进行了大幅度的调整,它的设计目标就是非常适合去进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比如说下载文件等,Volley的表现就会非常糟糕。

        这里我用一个例子来演示一下,volley在ListView中的使用,并且listVIew中有图片加载。

       主页面布局:activity_volley_json_image_test.xml

      

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/lv_volley"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"></ListView>
    <TextView
        android:id="@+id/txt_info"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="数据加载中......"
        android:textSize="18sp"
        android:gravity="center"
        android:visibility="gone"/>
</LinearLayout>

    ListView中item的布局
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/img_pic"
        android:layout_width="100dp"
        android:layout_height="100dp" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:orientation="vertical"
        android:layout_marginLeft="5dp">
        <TextView
            android:id="@+id/txt_title"
            android:layout_width="wrap_content"
            android:layout_height="49dp"
            android:text="这是标题"
            android:gravity="center_vertical"/>
        <TextView
            android:id="@+id/txt_time"
            android:layout_width="wrap_content"
            android:layout_height="49dp"
            android:text="2015-03-12"
            android:gravity="center_vertical"/>
    </LinearLayout>
</LinearLayout>

程序代码:Volley_Json_image_test
package com.example.cg.fangduo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class Volley_Json_image_test extends Activity {

    //定义listview
    private ListView lv_volley;
    //定义提示暂无数据
    private TextView txt_info;

    //定义volley请求
    public  RequestQueue  mQueue;

    //定义数据
    public List<Map<String, Object>> info;

    //定义列表的Adapter;
    public Volley_Json_image_Adapter volleyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_volley__json_image_test);

        initView();
    }

    /**
     * 初始化控件与信息
     */
    private void initView()
    {
        //初始化listview,初始时,因为数据从远程加载,所以在数据加载未完时,将listview设置为不可见
        lv_volley = (ListView)this.findViewById(R.id.lv_volley);
        lv_volley.setOnScrollListener(new ScrollListener());
        lv_volley.setVisibility(View.GONE);
        //初始化暂无数据,因为数据从远程加载,所以数据加载中的提示显示
        txt_info = (TextView)this.findViewById(R.id.txt_info);
        txt_info.setVisibility(View.VISIBLE);

        //初始化volley请求
        mQueue = Volley.newRequestQueue(this);
        //加载数据
        // [{"notepic":"http://image.baidu.com/i?ct=503316480&tn=baiduimagedetail&statnum=girl&ipn=d&z=0&fr=ala&s=0&ic=0&lm=-1&itg=0&cg=girl&word=%E7%BE%8E%E5%A5%B3%E5%9B%BE%E7%89%87&ie=utf-8&in=3354&cl=2&st=&pn=6&rn=1&di=&ln=31000&&fmq=1378374347070_R&se=&sme=0&tab=&face=&&is=0,132526&cs=0,0&adpicid=0&pi=14147590090&os=0&istype=&ist=&jit=&objurl=http%3A%2F%2Fc.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F377adab44aed2e7341c3f0578401a18b87d6faa7.jpg","noteTypeid":1,"noteid":1,"noteFast":0,"noteTitle":"欢迎来到这个神奇的世界","noteDateTime":"2014-7-6"},
        // {"notepic":"http://img3.imgtn.bdimg.com/it/u=2638575563,3145336706&fm=23&gp=0.jpg","noteTypeid":1,"noteid":2,"noteFast":0,"noteTitle":"今天好忙","noteDateTime":"2014-8-17"},
        // {"notepic":"http://img1.imgtn.bdimg.com/it/u=2816850553,3679993090&fm=23&gp=0.jpg","noteTypeid":1,"noteid":3,"noteFast":0,"noteTitle":"不想加班","noteDateTime":"2014-8-17"},
        // {"notepic":"http://img4.imgtn.bdimg.com/it/u=793795634,3401984036&fm=23&gp=0.jpg","noteTypeid":1,"noteid":4,"noteFast":0,"noteTitle":"美女图1","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img4.imgtn.bdimg.com/it/u=2978660446,2856475006&fm=23&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图2","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img5.imgtn.bdimg.com/it/u=1111035714,1878413225&fm=23&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图3","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img1.imgtn.bdimg.com/it/u=3981637234,1431600967&fm=23&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图4","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img3.imgtn.bdimg.com/it/u=1471976729,3245530376&fm=23&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图5","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img1.imgtn.bdimg.com/it/u=992411909,4001832108&fm=23&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图6","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img3.imgtn.bdimg.com/it/u=1438096542,2010064131&fm=23&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图7","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img1.imgtn.bdimg.com/it/u=2348235091,3744783718&fm=21&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图8","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img3.imgtn.bdimg.com/it/u=486736756,3902182809&fm=21&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图9","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img2.imgtn.bdimg.com/it/u=2671166332,507275986&fm=21&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图10","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img5.imgtn.bdimg.com/it/u=1857438318,1706082473&fm=21&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图11","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img0.imgtn.bdimg.com/it/u=547181070,2589863976&fm=21&gp=0.jpg","noteTypeid":1,"noteid":5,"noteFast":0,"noteTitle":"美女图12","noteDateTime":"2014-8-29"},
        // {"notepic":"http://img4.imgtn.bdimg.com/it/u=1319733707,1742255567&fm=11&gp=0.jpg","noteTypeid":1,"noteid":6,"noteFast":0,"noteTitle":"美女图13","noteDateTime":"2014-8-29"}]
        StringRequest jsonRequest = new StringRequest(Request.Method.GET,"http://172.31.0.163:9090/VolleyData.ashx?flag=1",
                new Response.Listener<String>(){

                    @Override
                    public void onResponse(String jsonObject) {

                        txt_info.setVisibility(View.GONE);
                        lv_volley.setVisibility(View.VISIBLE);
                        Log.v("Volley_Json_image_test:",jsonObject.toString());
                        info = getlistForJson(jsonObject);

                        volleyAdapter = new Volley_Json_image_Adapter(Volley_Json_image_test.this,info);

                        lv_volley.setAdapter(volleyAdapter);
                    }
                },
                new Response.ErrorListener(){

                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("onErrorResponse:",volleyError.toString());
                    }
                });
        mQueue.add(jsonRequest);
        //mQueue.start();
    }

    /**
     * 定义当ListViwe滚动时触发的事件
     */
    class ScrollListener implements AbsListView.OnScrollListener
    {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            int lastItemid = lv_volley.getLastVisiblePosition();

            if((lastItemid + 1) == totalItemCount)
            {
                //只有当列表数大于0(或是小于30时,加新数据。这个30是为了不让他重复加载)
                if(totalItemCount < 30 && totalItemCount > 0) {
                    //加载数据
                    StringRequest jsonRequest2 = new StringRequest(Request.Method.GET, "http://172.31.0.163:9090/VolleyData.ashx?flag=2",
                            new Response.Listener<String>() {

                                @Override
                                public void onResponse(String jsonObject) {
                                    info.addAll(getlistForJson(jsonObject));
                                    volleyAdapter.notifyDataSetChanged();
                                }
                            },
                            new Response.ErrorListener() {

                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Log.e("onErrorResponse:", volleyError.toString());
                                }
                            });


                     mQueue.add(jsonRequest2);

                }
            }
        }
    }


    /**
     * Json 转成 Map<>
     * @param jsonStr
     * @return
     */
    public static Map<String, Object> getMapForJson(String jsonStr){
        JSONObject jsonObject ;
        try {
            jsonObject = new JSONObject(jsonStr);

            Iterator<String> keyIter= jsonObject.keys();
            String key;
            Object value ;
            Map<String, Object> valueMap = new HashMap<String, Object>();
            while (keyIter.hasNext()) {
                key = keyIter.next();
                value = jsonObject.get(key);
                valueMap.put(key, value);
            }
            return valueMap;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            //Log.e(HttpClientUtils.TAG, e.toString());
        }
        return null;
    }
    /**
     * Json 转成 List<Map<>>
     * @param jsonStr
     * @return
     */
    public static List<Map<String, Object>> getlistForJson(String jsonStr){
        List<Map<String, Object>> list = null;
        try {
            JSONArray jsonArray = new JSONArray(jsonStr);
            JSONObject jsonObj ;
            list = new ArrayList<Map<String,Object>>();
            for(int i = 0 ; i < jsonArray.length() ; i ++){
                jsonObj = (JSONObject)jsonArray.get(i);
                list.add(getMapForJson(jsonObj.toString()));
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return list;
    }
}

listView的Adapter的代码:Volley_Json_image_Adapter
package com.example.cg.fangduo;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;

import java.util.List;
import java.util.Map;

/**
 * Created by cg on 2015/3/12.
 */
public class Volley_Json_image_Adapter extends BaseAdapter {

    private LayoutInflater inflater;
    //源数据
    private List<Map<String, Object>> jsonInfo;

    //定义volley
    private RequestQueue mQueue;
    private ImageLoader imageLoader;


    public Volley_Json_image_Adapter(Context context, List<Map<String, Object>> jsonInfo)
    {
        this.jsonInfo = jsonInfo;
        this.inflater = LayoutInflater.from(context);

        mQueue = Volley.newRequestQueue(context);
        imageLoader = new ImageLoader(mQueue,new BitmapCache(){
            @Override
            public Bitmap getBitmap(String s) {
                return null;
            }

            @Override
            public void putBitmap(String s, Bitmap bitmap) {

            }
        });
    }

    @Override
    public int getCount() {
        return jsonInfo.size();
    }

    @Override
    public Object getItem(int position) {
        return jsonInfo.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        VolleyInfo volleyInfo;
        if(convertView==null)
        {
            volleyInfo = new VolleyInfo();

            convertView = inflater.inflate(R.layout.lv_volley_item, null);
            volleyInfo.img_pic = (NetworkImageView)convertView.findViewById(R.id.img_pic);
            volleyInfo.txt_title = (TextView)convertView.findViewById(R.id.txt_title);
            volleyInfo.txt_time = (TextView)convertView.findViewById(R.id.txt_time);

            convertView.setTag(volleyInfo);
        }else
        {
            volleyInfo = (VolleyInfo)convertView.getTag();
        }

        volleyInfo.txt_title.setText(jsonInfo.get(position).get("noteTitle").toString());
        volleyInfo.txt_time.setText(jsonInfo.get(position).get("noteDateTime").toString());
        //为图片控件加载图片,采用NetworkImageView控件。
        //第一项是加载图片控件的默认图片,一般是图片加载中,这样的图片
        //第二项是当发生错误的时候加载的图片,如网络图片路径不对或是加载失败的时候显示的图片
        //第三项就是加载网络图片了
        volleyInfo.img_pic.setDefaultImageResId(R.drawable.noimg);
        volleyInfo.img_pic.setErrorImageResId(R.drawable.a01);
        volleyInfo.img_pic.setImageUrl(jsonInfo.get(position).get("notepic").toString(),imageLoader);
        return convertView;
    }


    public class VolleyInfo
    {
        NetworkImageView img_pic;
        TextView txt_title;
        TextView txt_time;
    }

    /**
     * 对图片进行防OOM处理
     */
    public class BitmapCache implements ImageLoader.ImageCache{

        private LruCache<String,Bitmap> mCache;

        public BitmapCache(){
            int maxSize = 10*1024*1024;
            mCache = new LruCache<String, Bitmap>(maxSize){
                protected int sizeOf(String key,Bitmap bitmap)
                {
                    return bitmap.getRowBytes() * bitmap.getHeight();
                }
            };
        }

        @Override
        public Bitmap getBitmap(String url) {
            return mCache.get(url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            mCache.put(url,bitmap);
        }
    }
}

如果你想对Volley了解的更细一点,请参看:
http://blog.csdn.net/guolin_blog/article/details/17482095

 
 

你可能感兴趣的:(android中volley的应用)