安卓新的連網方式 Volley的使用(一)載入圖片與 json

來源:互聯網
上載者:User

標籤:style   blog   http   color   java   使用   strong   io   

最近剛接觸安卓, 以前搞wp ,一對比起來 ,安卓怎麼這麼麻煩。連網必須要重新開一個線程才可以。而且載入網狀圖片也很麻煩。。。花了很久一直卡在快速滑動載入網狀圖片的listview上面 ,一直很糾結痛苦。。。

 

but 今天發現了 新的連網方式,感激Google啊。Volley 

忽然發現以前那些 HttpClient或者HttpUrlConnection 都去死吧 。。還是你好用啊。。

用法  

ImageVIew 載入圖片

核心ImageRequest

1首先  

private RequestQueue mQueue;       

2在OnCreate方法中對其進行初始化

mQueue = Volley.newRequestQueue(this); 

3   建立ImageRequest對象,並將其添加到mQueue中

public void readBitmapViaVolley(String imgUrl, final ImageView imageView) {ImageRequest imgRequest = new ImageRequest(imgUrl,new Response.Listener<Bitmap>() {@Overridepublic void onResponse(Bitmap arg0) {// TODO Auto-generated method stubimageView.setImageBitmap(arg0);}},   //紫色代碼 表示  連網成功後的回調300, 200, Config.ARGB_8888, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {}});  //連網失敗後 的回調。mQueue.add(imgRequest); //添加到mQueue中,完成綁定。
 }

 

  在上面,我們可以看到,在ImageRequest的建構函式中,我們就可以直接將一些關於Bitmap的參數給傳進去了,比如長寬等資訊,然後在其返回的Response.Listener中獲得返回的結果,就是一個Bitmap了,並在onResponse函數中對ImageView進行設定,最後將其添加到mQueue中。

上面的代碼  和httpclient 與HttpUrlConnection  在多線程中訪問圖片的效果是一樣的,只是代碼簡潔了很多。。哈哈 再一次感謝Google。

ImageVIew 載入Json

首先 老樣子

private RequestQueue mQueue;

mQueue = Volley.newRequestQueue(this); 

 

public void getWeatherInfo(){JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(WEATHER_LINK, null, new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject arg0) {list.clear();Iterator<String> it = arg0.keys();while(it.hasNext()){String key = it.next();JSONObject obj = null;try { obj = arg0.getJSONObject(key);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (obj != null) {Iterator<String> objIt = obj.keys();while (objIt.hasNext()) {String objKey = objIt.next();String objValue;try {objValue = obj.getString(objKey);HashMap<String, String> map = new HashMap<String, String>();map.put("title", objKey);map.put("content", objValue);Log.v(TAG, "title = " + objKey + " | content = " + objValue);list.add(map);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}Log.v(TAG, "list.size = " + list.size());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {}});mQueue.add(jsonObjectRequest);

  

 根據json 資料的不同  ,可以使用  JsonArrayRequest  或者JsonObjectRequest

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.