Android網絡通信必備神器Volley詳解——發送一個標準的Request

Volley主要支持一下幾種Request

1. StringRequest:確定一個URL,獲得返回的原始字符串。

2. ImageRequest:確定一個URL,獲得一個圖片。

3. JsonObjectRequest和JsonArrayRequest: 確定一個URL,獲得JSON對象或者數字。


請求一個圖片


使用ImageRequest

<span style="font-size:14px;">ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
...

// Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
    new Response.Listener<Bitmap>() {
        @Override
       <strong> public void onResponse(Bitmap bitmap) {
            mImageView.setImageBitmap(bitmap);
        }</strong>
    }, 0, 0, null,
    new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            mImageView.setImageResource(R.drawable.image_load_error);
        }
    });
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(request);</span>

使用ImageLoader和NetworkImageView

使用ImageLoader 和NetworkImageView來有效的加載多張圖片,比如在ListView中加載圖片。
在你layout的XML文件中
<com.android.volley.toolbox.NetworkImageView
        android:id="@+id/networkImageView"
        android:layout_width="150dp"
        android:layout_height="170dp"
        android:layout_centerHorizontal="true" />

加載圖片
ImageLoader mImageLoader;
NetworkImageView mNetworkImageView;
private static final String IMAGE_URL =
    "http://developer.android.com/images/training/system-ui.png";
...

// Get the NetworkImageView that will display the image.
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);

// Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader();

// Set the URL of the image that should be loaded into this view, and
// specify the ImageLoader that will be used to make the request.
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);

正如上篇文章裏說的,把RequestQueue封裝起來使得圖片的cache獨立於Activity,當屏幕進行旋轉的時候圖片不用重新從網絡下載,不會造成閃屏。

請求JSON

與前面的Request類似,直接看代碼
TextView mTxtDisplay;
ImageView mImageView;
mTxtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://my-json-feed";

JsonObjectRequest jsObjRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        mTxtDisplay.setText("Response: " + response.toString());
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub

    }
});

// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章