Volley simple learning and use 1, Volley simple learning and use
I. Introduction:Volley combines the advantages of AsyncHttpClient and Universal-Image-Loader to implement HTTP Communication as easily as AsyncHttpClient, you can also easily attach images on the network like Universal-Image-Loader. In addition to ease of use, Volley has also made significant adjustments in terms of performance. Its design goal is to be very suitable for performing a small amount of data, but frequent network operations, for network operations that involve a large amount of data, such as file downloads, Volley performs very poorly.
Volley should simplify the development of network communication, especially for the following two situations:
- JSON object
- Image loading
Ii. Simple use:(1) For a simple GET request, the returned data type is String1. Remember to add network permissions.
<uses-permissionandroid:name="android.permission.INTERNET"/>
2. Simple Procedure
Private RequestQueue mRequestQueue; // create a RequestQueue mRequestQueue = Volley. newRequestQueue (this); // create a StringRequest --- GET request String url = "http://www.baidu.com"; StringRequest stringRequest = new StringRequest (url, new Response. listener <String> () {@ Override public void onResponse (String response) {Log. d (TAG, response) ;}}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError error) {Log. e (TAG, error. getMessage () ;}}); // Add the StringRequest object to RequestQueue mRequestQueue. add (stringRequest );3. The result returns a string of Html source code.
(2) A simple json get Request, similar to the same method. Here we use another Request constructor.
String jsonurl = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json"; Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.i(TAG, response.toString()); } }; Response.ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.i(TAG, error.getMessage()); } }; JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET, jsonurl, null, listener, errorListener); mRequestQueue.add(jr);(3) simple POST requests
JsonObjectRequest postRequest = new JsonObjectRequest (Request. method. POST, jsonurl, null, listener, errorListener) {// write the Post parameter to the map @ Override protected Map <String, String> getParams () throws AuthFailureError {Map <String, string> map = new HashMap <String, String> (); map. put ("params1", "value1"); map. put ("params2", "value2"); return map ;}}; mRequestQueue. add (postRequest );3. Use ImageRequest to load images. The process is similar
String imageUrl = "http://a.hiphotos.baidu.com/image/pic/item/3801213fb80e7bec5cfb43e02d2eb9389b506b89.jpg"; int max_width = 300; int max_height = 300; Response.Listener<Bitmap> listener = new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap response) { myImageView.setImageBitmap(response); } }; Response.ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { myImageView.setImageResource(R.drawable.default_pg); } }; ImageRequest imageRequest = new ImageRequest(imageUrl, listener, max_width, max_height, Config.RGB_565, errorListener); mRequestQueue.add(imageRequest);The parameter meanings in ImageRequest are as follows:
* @param url URL of the image * @param listener Listener to receive the decoded bitmap * @param maxWidth Maximum width to decode this bitmap to, or zero for none * @param maxHeight Maximum height to decode this bitmap to, or zero for * none * @param decodeConfig Format to decode the bitmap to * @param errorListener Error listener, or null to ignore errors
Note: 1. maxWidth and maxHeight indicate the maximum image width and height. If the image size is exceeded, the image will be compressed. If it is set to 0, the image will not be compressed and loaded directly; 2. decodeConfig indicates the color attribute of the image, Bitmap. several constants in Config can be used here. ARGB_8888 can display the best color attributes, and each image pixel occupies 4 bytes, RGB_565 indicates that each image pixel occupies 2 bytes.
(2) Using ImageLoader to implement ImageLoader can also be used to load images on the network, and it is also implemented using ImageRequest internally. However, ImageLoader is obviously more efficient than ImageRequest, it not only caches images, but also filters out duplicate links to avoid repeated requests.
// The first step is to create RequestQueue, which has been created earlier. Here, the String imageUrl = "http://a.hiphotos.baidu.com/image/pic/item/3801213fb80e7bec5cfb43e02d2eb9389b506b89.jpg" is not created again; // create LruCache to save the downloaded image final LruCache <String, bitmap> mImageLruCache = new LruCache <String, Bitmap> (20); // create ImageCache for future use of ImageCache imageCache = new ImageCache () {@ Override public void putBitmap (String url, bitmap bitmap) {mImageLruCache. put (url, bitmap) ;}@ Override public Bitmap getBitmap (String url) {return mImageLruCache. get (url) ;}}; // create ImageLoader imageLoader = new ImageLoader (mRequestQueue, imageCache);/*** @ param imageView The imageView that the listener is associated. * @ param defaultImageResId Default image resource ID to use, or 0 if it doesn' t exist. * @ param errorImageResId Error image resource ID to use, or 0 if it doesn' t exist. * /// obtain an ImageListener object ImageListener imageListener = ImageLoader. getImageListener (myImageView, R. drawable. default_pg, R. drawable. failed_pg); // call the get () method of ImageLoader to load the image imageLoader on the network. get (imageUrl, imageListener); // if you want to limit the size of an image to be loaded, use another method of get () to reload imageLoader. get (imageUrl, imageListener, 300,300 );One of the best practices that ImageLoader can provide is to provide image caching. Here we use LruCache to achieve this. The maximum number of cached images is 20; you can also customize the memory size of the maximum cached image, as shown below:
final LruCache<String, Bitmap> mImageLruCache = new LruCache<String, Bitmap>(maxSize){ @Override protected int sizeOf(String url, Bitmap bitmap){ return bitmap.getRowBytes() * bitmap.getHeight(); } }; ImageCache imageCache = new ImageCache() { @Override public void putBitmap(String url, Bitmap bitmap) { mImageLruCache.put(url, bitmap); } @Override public Bitmap getBitmap(String url) { return mImageLruCache.get(url); } };In this way, an LruCache with a maximum cache size of 10 MB and a LRU policy is created. (3) Use NetworkImageView method 1. First, use the control in XML Layout
<com.android.volley.toolbox.NetworkImageView android:id="@+id/myNetworkImageView" android:layout_width="300dp" android:layout_height="300dp" android:contentDescription="@string/hello_world" />
The downloaded image will be compressed according to the width and height. If you do not want to compress the image, you can use wrap content2 and then use NetworkImageView in the code.
// The ImageLoader created earlier is the same as the previous one, and will not be created again // use NetworkImageView imageView = (NetworkImageView) findViewById (R. id. myNetworkImageView); imageView. setDefaultImageResId (R. drawable. default_pg); imageView. setErrorImageResId (R. drawable. failed_pg); imageView. setImageUrl (imageUrl, imageLoader );