Volley的使用

标签: androidvolleyjsonlistview网络
524人阅读 评论(0) 收藏 举报
分类:

以下是在我的项目中,Volley的使用,自己的经验、用法的总结以及记录:
1、Volley请求服务器返回JsonObject:

RequestQueue  mQueue = Volley.newRequestQueue(this);
    JsonObjectRequest json = new JsonObjectRequest(del, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jsonObject) {
            try {
                delstatus = jsonObject.getString("status");
                delinfo = jsonObject.getString("info");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if ("true".equals(delstatus)) {
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
        }
    });
    mQueue.add(json);
}

2、Volley请求服务器返回JsonArray:

private void GetArray(){
    RequestQueue queue = Volley.newRequestQueue(this);
    String str = "";   //请求服务器的网址
    JsonArrayRequest json = new JsonArrayRequest(str, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray jsonArray) {
            for (int i = 0; i <jsonArray.length() ; i++) {
                try {
                    JSONObject item = jsonArray.getJSONObject(i);
                    String name = item.getString("name");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
        }
    });
    queue.add(json);
}

3、Volley Post数据到服务器,Post的数据放入到Map中,返回一个JsonObject:
首先,重写Request:

/**
 * 重写volley的Post请求,可Post Map,返回一个JsonObject
 */

public class JsonObjectPostRequest extends Request<JSONObject> {

    private Map<String,String> mMap;
    private Response.Listener<JSONObject> mListener;


    public JsonObjectPostRequest(String url,Response.Listener<JSONObject> listener, Response.ErrorListener errorListener,Map map) {
        super(Request.Method.POST, url, errorListener);
        mListener=listener;
        mMap=map;

    }
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {

        return mMap;
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        mListener.onResponse(response);

    }

调用:

/**
* 登录验证
* */
private void  checklogin(){

    RequestQueue mqueue = Volley.newRequestQueue(this);
    final Map<String,String> map = new HashMap<>();
    map.put("user",username);
    map.put("pwd",userpassword);
    JsonObjectPostRequest jsonpost = new JsonObjectPostRequest(Baseurl.Post_login, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jsonObject) {
            try {
                status = jsonObject.getString("status");
                item = jsonObject.getJSONObject("results");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if ("true".equals(status)) {
                intent.setClass(context, MainActivity.class);
                startActivity(intent);
                finish();
                ToastUtil.showToast(context, "登陆成功");
                DialogUtil.closedialog();
            }else {
                ToastUtil.showToast(context, "用户名或密码错误");
                DialogUtil.closedialog();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
        }
    },map);
    mqueue.add(jsonpost);
}

4、Volley Post数据到服务器,Post的数据放入到Map中,返回一个JsonArray:
首先,重写Request(调用方法跟返回JsonObject的一样):

/**
 * 重写volley的Post请求,可Post Map,返回一个JsonArray
 */
public class JsonArrayPostRequest extends Request<JSONArray>{

    private Map<String,String> mMap;
    private Response.Listener<JSONArray> mListener;
    private LruCache lrucache;


    public JsonArrayPostRequest(String url,Response.Listener<JSONArray> listener, Response.ErrorListener errorListener,Map map) {
        super(Request.Method.POST, url, errorListener);
        mListener=listener;
        mMap=map;
    }
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mMap;
    }

    @Override
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONArray(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONArray response) {
        mListener.onResponse(response);

    }
}

5、Volley加载图片到listview中,Volley加载图片又几种方式,这里用NetworkImageView,首先布局里面的Imageview应该引用NetworkImageView,
然后在Adapter里面:

public class VolleyListAdapter extends BaseAdapter {
   private RequestQueue mQueue;
   private ImageLoader mImageLoader;
   private LayoutInflater mInflater;
   private List<BaseBeams> items;

   public VolleyListAdapter(Context context,  List<BaseBeams> itemList) {
      super();
      mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      this.items = itemList;
      mQueue = Volley.newRequestQueue(context);
      mImageLoader = new ImageLoader(mQueue, new BitmapCache());
   }

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

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

   @Override
   public long getItemId(int position) {
      return items.get(position).getId();
   }

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
      if (convertView == null) {
         convertView = mInflater.inflate(R.layout.image_item_one, null);
         holder = new ViewHolder();
         holder.imageView = (NetworkImageView) convertView.findViewById(R.id.imageView);
         holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
         holder.textView2 = (TextView) convertView.findViewById(R.id.textView2);
         convertView.setTag(holder);
      }else {
         holder = (ViewHolder) convertView.getTag();
      }
      BaseBeams item = items.get(position);
      holder.textView1.setText(item.getTitle());
      holder.textView2.setText(item.getInfo());
      /**
       * Volley加载图片,避免了图片错位
       * */
      final String imgurl = item.getImgUrl();
      if (imgurl != null && !imgurl.equals("")) {
         holder.imageView.setDefaultImageResId(R.mipmap.download);       //加载中的图片
         holder.imageView.setErrorImageResId(R.mipmap.erro_download);    //加载失败的图片
         holder.imageView.setImageUrl(item.getImgUrl(), mImageLoader);   //加载完成的图片
         holder.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
      }
      return convertView;
   }

   private static class ViewHolder {
      private NetworkImageView imageView;
      private TextView textView1, textView2;
   }

}

然后在activity中引用:

/*
* 获取listview的信息
* */

private void GetList(){

    path = "";
    JsonObjectRequest json = new JsonObjectRequest(path, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jsonObject) {
            try {
                status = jsonObject.getString("status");
                info1 = jsonObject.getString("info");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if ("true".equals(status)) {
                try {
                    jsonArray = jsonObject.getJSONArray("results");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        item = jsonArray.getJSONObject(i);
                        title = item.getString("title");
                        info = item.getString("info");
                        imageurl = item.getString("img");
                        myid = item.getInt("id");

                        baseBeams = new BaseBeams();
                        baseBeams.setTitle(title);
                        baseBeams.setInfo(info);
                        baseBeams.setHint(myid + "");
                        baseBeams.setImgUrl(imageurl);
                        baseBeams.setNull(mcheck);
                        list.add(baseBeams);
                    }              
                 mAdapter = new VolleyListAdapter(context,list);
                 main_user_collect_listview.setAdapter(mAdapter);
                 mAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } 
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
        }
    });
    mQueue.add(json);
}
public class BitmapCache implements ImageCache {
   private LruCache<String, Bitmap> mCache;

   public BitmapCache() {
      if (mCache == null) {
         int maxSize = 10 * 1024 * 1024;
         mCache = new LruCache<String, Bitmap>(maxSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
               return bitmap.getByteCount();
            }
         };
      }
   }

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

   @Override
   public void putBitmap(String url, Bitmap bitmap) {
      if (bitmap != null) {
         mCache.put(url, bitmap);
      }
   }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:91428次
    • 积分:1299
    • 等级:
    • 排名:千里之外
    • 原创:54篇
    • 转载:0篇
    • 译文:0篇
    • 评论:47条
    最新评论