菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
405
0

Volley HTTP库系列教程(4)Volley内置的几种请求介绍及示例,StringRequest,ImageRequest,JsonObjectRequest

原创
05/13 14:22
阅读数 29373

Making a Standard Request

1.This lesson teaches you to

  1. Request a String  返回String
  2. Request an Image  返回Image
  3. Request JSON     返回Json

VIDEO

  Volley: Easy, Fast Networking for Android

  This lesson describes how to use the common request types that Volley supports:

  • StringRequest. Specify a URL and receive a raw string in response. See Setting Up a Request Queue for an example.
  • ImageRequest. Specify a URL and receive an image in response.
  • JsonObjectRequest and JsonArrayRequest (both subclasses of JsonRequest). Specify a URL and get a JSON object or array (respectively) in response.

  If your expected response is one of these types, you probably won't have to implement a custom request. This lesson describes how to use these standard request types. For information on how to implement your own custom request, see Implementing a Custom Request.

2.Request a String

 1 String url ="http://www.myurl.com";
 2 
 3 // Formulate the request and handle the response.
 4 StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
 5         new Response.Listener<String>() {
 6     @Override
 7     public void onResponse(String response) {
 8         // Do something with the response
 9     }
10 },
11     new Response.ErrorListener() {
12         @Override
13         public void onErrorResponse(VolleyError error) {
14             // Handle error
15     }
16 });
17 
18 // Add the request to the RequestQueue.
19 mRequestQueue.add(stringRequest);

3.Request an Image

3.1 简介

  Volley offers the following classes for requesting images. These classes layer on top of each other to offer different levels of support for processing images:

  • ImageRequest—a canned request for getting an image at a given URL and calling back with a decoded bitmap. It also provides convenience features like specifying a size to resize to. Its main benefit is that Volley's thread scheduling ensures that expensive image operations (decoding, resizing) automatically happen on a worker thread.
  • ImageLoader—a helper class that handles loading and caching images from remote URLs. ImageLoaderis a an orchestrator for large numbers of ImageRequests, for example when putting multiple thumbnails in a ListViewImageLoader provides an in-memory cache to sit in front of the normal Volley cache, which is important to prevent flickering. This makes it possible to achieve a cache hit without blocking or deferring off the main thread, which is impossible when using disk I/O. ImageLoader also does response coalescing, without which almost every response handler would set a bitmap on a view and cause a layout pass per image. Coalescing makes it possible to deliver multiple responses simultaneously, which improves performance.
  • NetworkImageView—builds on ImageLoader and effectively replaces ImageView for situations where your image is being fetched over the network via URL. NetworkImageView also manages canceling pending requests if the view is detached from the hierarchy.

3.2 Use ImageRequest

  Here is an example of using ImageRequest. It retrieves the image specified by the URL and displays it in the app. Note that this snippet interacts with the RequestQueue through a singleton class (see Setting Up a RequestQueue for more discussion of this topic):

 1 ImageView mImageView;
 2 String url = "http://i.imgur.com/7spzG.png";
 3 mImageView = (ImageView) findViewById(R.id.myImage);
 4 ...
 5 
 6 // Retrieves an image specified by the URL, displays it in the UI.
 7 ImageRequest request = new ImageRequest(url,
 8     new Response.Listener<Bitmap>() {
 9         @Override
10         public void onResponse(Bitmap bitmap) {
11             mImageView.setImageBitmap(bitmap);
12         }
13     }, 0, 0, null,
14     new Response.ErrorListener() {
15         public void onErrorResponse(VolleyError error) {
16             mImageView.setImageResource(R.drawable.image_load_error);
17         }
18     });
19 // Access the RequestQueue through your singleton class.
20 MySingleton.getInstance(this).addToRequestQueue(request);

3.3 Use ImageLoader and NetworkImageView

  You can use ImageLoader and NetworkImageView in concert to efficiently manage the display of multiple images, such as in a ListView. In your layout XML file, you use NetworkImageView in much the same way you would use ImageView, for example:

<com.android.volley.toolbox.NetworkImageView
        android:id="@+id/networkImageView"
        android:layout_width="150dp"
        android:layout_height="170dp"
        android:layout_centerHorizontal="true" />

  You can use ImageLoader by itself to display an image, for example:

 1 ImageLoader mImageLoader;
 2 ImageView mImageView;
 3 // The URL for the image that is being loaded.
 4 private static final String IMAGE_URL =
 5     "http://developer.android.com/images/training/system-ui.png";
 6 ...
 7 mImageView = (ImageView) findViewById(R.id.regularImageView);
 8 
 9 // Get the ImageLoader through your singleton class.
10 mImageLoader = MySingleton.getInstance(this).getImageLoader();
11 mImageLoader.get(IMAGE_URL, ImageLoader.getImageListener(mImageView,
12          R.drawable.def_image, R.drawable.err_image));

  However, NetworkImageView can do this for you if all you're doing is populating an ImageView. For example:

 1 ImageLoader mImageLoader;
 2 NetworkImageView mNetworkImageView;
 3 private static final String IMAGE_URL =
 4     "http://developer.android.com/images/training/system-ui.png";
 5 ...
 6 
 7 // Get the NetworkImageView that will display the image.
 8 mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
 9 
10 // Get the ImageLoader through your singleton class.
11 mImageLoader = MySingleton.getInstance(this).getImageLoader();
12 
13 // Set the URL of the image that should be loaded into this view, and
14 // specify the ImageLoader that will be used to make the request.
15 mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);

  The above snippets access the RequestQueue and the ImageLoader through a singleton class, as described in Setting Up a RequestQueue. This approach ensures that your app creates single instances of these classes that last the lifetime of your app. The reason that this is important for ImageLoader (the helper class that handles loading and caching images) is that the main function of the in-memory cache is to allow for flickerless rotation. Using a singleton pattern allows the bitmap cache to outlive the activity. If instead you create theImageLoader in an activity, the ImageLoader would be recreated along with the activity every time the user rotates the device. This would cause flickering.

3.4 Example LRU cache

  The Volley toolbox provides a standard cache implementation via the DiskBasedCache class. This class caches files directly onto the hard disk in the specified directory. But to use ImageLoader, you should provide a custom in-memory LRU bitmap cache that implements the ImageLoader.ImageCache interface. You may want to set up your cache as a singleton; for more discussion of this topic, see Setting Up a RequestQueue.

  Here is a sample implementation for an in-memory LruBitmapCache class. It extends the LruCache class and implements the ImageLoader.ImageCache interface:

 1 import android.graphics.Bitmap;
 2 import android.support.v4.util.LruCache;
 3 import android.util.DisplayMetrics;
 4 import com.android.volley.toolbox.ImageLoader.ImageCache;
 5 
 6 public class LruBitmapCache extends LruCache<String, Bitmap>
 7         implements ImageCache {
 8 
 9     public LruBitmapCache(int maxSize) {
10         super(maxSize);
11     }
12 
13     public LruBitmapCache(Context ctx) {
14         this(getCacheSize(ctx));
15     }
16 
17     @Override
18     protected int sizeOf(String key, Bitmap value) {
19         return value.getRowBytes() * value.getHeight();
20     }
21 
22     @Override
23     public Bitmap getBitmap(String url) {
24         return get(url);
25     }
26 
27     @Override
28     public void putBitmap(String url, Bitmap bitmap) {
29         put(url, bitmap);
30     }
31 
32     // Returns a cache size equal to approximately three screens worth of images.
33     public static int getCacheSize(Context ctx) {
34         final DisplayMetrics displayMetrics = ctx.getResources().
35                 getDisplayMetrics();
36         final int screenWidth = displayMetrics.widthPixels;
37         final int screenHeight = displayMetrics.heightPixels;
38         // 4 bytes per pixel
39         final int screenBytes = screenWidth * screenHeight * 4;
40 
41         return screenBytes * 3;
42     }
43 }

  Here is an example of how to instantiate an ImageLoader to use this cache:

1 RequestQueue mRequestQueue; // assume this exists.
2 ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(
3             LruBitmapCache.getCacheSize()));

4.Request JSON

  Volley provides the following classes for JSON requests:

  • JsonArrayRequest—A request for retrieving a JSONArray response body at a given URL.
  • JsonObjectRequest—A request for retrieving a JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.

  Both classes are based on the common base class JsonRequest. You use them following the same basic pattern you use for other types of requests. For example, this snippet fetches a JSON feed and displays it as text in the UI:

 1 TextView mTxtDisplay;
 2 ImageView mImageView;
 3 mTxtDisplay = (TextView) findViewById(R.id.txtDisplay);
 4 String url = "http://my-json-feed";
 5 
 6 JsonObjectRequest jsObjRequest = new JsonObjectRequest
 7         (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
 8 
 9     @Override
10     public void onResponse(JSONObject response) {
11         mTxtDisplay.setText("Response: " + response.toString());
12     }
13 }, new Response.ErrorListener() {
14 
15     @Override
16     public void onErrorResponse(VolleyError error) {
17         // TODO Auto-generated method stub
18 
19     }
20 });
21 
22 // Access the RequestQueue through your singleton class.
23 MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
  For an example of implementing a custom JSON request based on Gson, see the next lesson, Implementing a Custom Request.
 
 
 

发表评论

0/200
405 点赞
0 评论
收藏
为你推荐 换一批