Volley基本使用
Posted 小阿仙的fans
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Volley基本使用相关的知识,希望对你有一定的参考价值。
ImageLoader异步加载图片
1 /** 2 * 异步加载图片 3 */ 4 private void loadImageByVolley(){ 5 String imageUrl="http://www.taopic.com/uploads/allimg/120421/107063-12042114025737.jpg"; 6 RequestQueue requestQueue = Volley.newRequestQueue(this); 7 8 final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(20); 9 ImageCache imageCache = new ImageCache() { 10 11 @Override 12 public void putBitmap(String key, Bitmap value) { 13 lruCache.put(key, value); 14 } 15 16 @Override 17 public Bitmap getBitmap(String key) { 18 return lruCache.get(key); 19 } 20 }; 21 ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache); 22 23 //三个参数分别是imageView组件,默认图片,加载失败图片 24 ImageListener listener = ImageLoader.getImageListener(iv, R.drawable.ic_launcher,0); 25 imageLoader.get(imageUrl, listener); 26 }
NetworkImageView显示网络图片
1 /** 2 * 使用NetworkImageView显示网络图片,代替传统的ImageView 3 */ 4 private void showImageByNetworkImageView(){ 5 String imageUrl="http://avatar.csdn.net/6/6/D/1_lfdfhl.jpg"; 6 RequestQueue requestQueue = Volley.newRequestQueue(this); 7 final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(20); 8 ImageCache imageCache = new ImageCache() { 9 @Override 10 public void putBitmap(String key, Bitmap value) { 11 lruCache.put(key, value); 12 } 13 14 @Override 15 public Bitmap getBitmap(String key) { 16 return lruCache.get(key); 17 } 18 }; 19 ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache); 20 mNetworkImageView.setImageUrl(imageUrl,imageLoader); 21 }
处理get请求
1 public class Weather { 2 3 @SerializedName("code") 4 private String code; 5 6 @SerializedName("list") 7 private WeatherList list; 8 9 @SerializedName("day") 10 private String[] day; 11 12 13 public WeatherList getList() { 14 return list; 15 } 16 17 public void setList(WeatherList list) { 18 this.list = list; 19 } 20 21 public String getCode() { 22 return code; 23 } 24 25 public void setCode(String code) { 26 this.code = code; 27 } 28 29 public String[] getDay() { 30 return day; 31 } 32 33 public void setDay(String[] day) { 34 this.day = day; 35 } 36 37 38 39 }
1 public class Test extends Activity { 2 private String url = "http://api.izhuzhou.com.cn/GetMoreWeather.ashx"; 3 private TextView tv; 4 5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.test); 9 10 tv = (TextView) findViewById(R.id.text); 11 12 RequestQueue mQueue = Volley.newRequestQueue(this); 13 mQueue.add(new JsonObjectRequest(Method.GET, url, null, new Listener<JSONObject>() { 14 public void onResponse(JSONObject response) { 15 Gson gson = new Gson(); 16 Weather weather = gson.fromJson(response.toString(), Weather.class); 17 weather.getCode(); 18 weather.getList().getUpdateTime(); 19 20 tv.setText(weather.getDay()[0]); 21 22 } 23 24 }, null)); 25 mQueue.start(); 26 27 } 28 29 }
以上是关于Volley基本使用的主要内容,如果未能解决你的问题,请参考以下文章