Complete parsing of Android Volley (2) using Volley to load network images

Source: Internet
Author: User

Reprinted please indicate the source: http://blog.csdn.net/guolin_blog/article/details/17482165

In the previous article, we learned what Volley is and its basic usage. In this article, we will learn more about Volley's advanced usage. If you have not read my previous article, we recommend that you read it first.Complete analysis of Android Volley (1), basic usage of Volley.

As mentioned in the previous article, Volley is a framework that integrates the advantages of AsyncHttpClient and Universal-Image-Loader. We all know that Universal-Image-Loader has a very powerful function for loading network images, and Volley can achieve similar results, in addition, the performance is not inferior to that of Universal-Image-Loader. Let's take a look at it.

1. ImageRequest usage

We have learned how to use StringRequest and JsonRequest, and have concluded that their usage is very similar. You can perform the following three steps:

1. Create a RequestQueue object.

2. Create a Request object.

3. Add the Request object to RequestQueue.

The StringRequest and JsonRequest are inherited from the Request, so their usage is similar. So needless to say, today we are going to learn ImageRequest, I believe you have guessed it from the name, it also inherits from the Request, so its usage is also basically the same, first, you must obtain a RequestQueue object. You can call the following method to obtain it:

RequestQueue mQueue = Volley.newRequestQueue(context);
Next, we need to create an ImageRequest object. The Code is as follows:
ImageRequest imageRequest = new ImageRequest("http://developer.android.com/images/home/aw_dac.png",new Response.Listener<Bitmap>() {@Overridepublic void onResponse(Bitmap response) {imageView.setImageBitmap(response);}}, 0, 0, Config.RGB_565, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {imageView.setImageResource(R.drawable.default_image);}});
As you can see, the ImageRequest constructor receives six parameters. The first parameter is the image URL address. There is nothing to explain. The second parameter is the successful callback of the image request. Here we set the returned Bitmap parameter to ImageView. The third and fourth parameters are used to specify the maximum width and height of the image. If the width or height of the specified network image is greater than the maximum value, the image is compressed, if it is set to 0, the image will not be compressed regardless of the size of the image. The fifth parameter is used to specify 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. The sixth parameter is the callback for image request failure. Here, a default image is displayed in ImageView when the request fails.

Add the ImageRequest object to RequestQueue as follows:

mQueue.add(imageRequest);
Now, if you run the program and try to send such a network request, you will soon be able to see the picture on the network displayed in ImageView, as shown in:


2. ImageLoader usage

If you think ImageRequest is already very useful, I can only say that you are too easy to satisfy pai_^. In fact, Volley can do more than that in requesting network images, and ImageLoader is a good example. 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.

Since ImageLoader does not inherit from the Request, its usage is different from what we have learned. In summary, it can be divided into the following four steps:

1. Create a RequestQueue object.

2. Create an ImageLoader object.

3. Get an ImageListener object.

4. Call the get () method of ImageLoader to load images on the network.

Next we will follow this step to learn how to use ImageLoader. First, we have already written the first step to create a RequestQueue object many times. I believe we don't have to repeat it. So let's start with Step 2 and create an ImageLoader object, the Code is as follows:

ImageLoader imageLoader = new ImageLoader(mQueue, new ImageCache() {@Overridepublic void putBitmap(String url, Bitmap bitmap) {}@Overridepublic Bitmap getBitmap(String url) {return null;}});
As you can see, the ImageLoader constructor receives two parameters. The first parameter is the RequestQueue object, and the second parameter is an ImageCache object. Here we first create an empty ImageCache implementation.

Next, you need to obtain an ImageListener object. The Code is as follows:

ImageListener listener = ImageLoader.getImageListener(imageView,R.drawable.default_image, R.drawable.failed_image);
By calling the getImageListener () method of ImageLoader, we can obtain an ImageListener object. The getImageListener () method receives three parameters. The first parameter specifies the ImageView control used to display images, the second parameter specifies the image displayed when the image is loaded, and the third parameter specifies the image displayed when the image fails to be loaded.

Finally, call the get () method of ImageLoader to load the image. The Code is as follows:

imageLoader.get("http://img.my.csdn.net/uploads/201404/13/1397393290_5765.jpeg", listener);

The get () method receives two parameters. The first parameter is the image URL, and the second parameter is the obtained ImageListener object. Of course, if you want to limit the image size, you can also use the get () method to reload it to specify the maximum width and height allowed by the image, as shown below:

imageLoader.get("http://img.my.csdn.net/uploads/201404/13/1397393290_5765.jpeg",listener, 200, 200);

Run the program and start to load the image. You will see a default image in the ImageView. After the image on the network is loaded, the ImageView will automatically display the image, shows the effect.


Although we have mastered the usage of ImageLoader, the advantages of ImageLoader just introduced have not yet been used. Why? Because the ImageCache object created here is an empty implementation, it does not play a role in image caching. Writing an ImageCache is also very simple, but if you want to write an ImageCache with excellent performance, you 'd better use the LruCache function provided by Android. If you do not know about LruCache, refer to my previous blogAndroid efficiently loads large charts and multi-graph solutions, effectively avoiding program OOM.

Here we create a BitmapCache and implement the ImageCache interface, as shown below:

public class BitmapCache implements ImageCache {private LruCache<String, Bitmap> mCache;public BitmapCache() {int maxSize = 10 * 1024 * 1024;mCache = new LruCache<String, Bitmap>(maxSize) {@Overrideprotected int sizeOf(String key, Bitmap bitmap) {return bitmap.getRowBytes() * bitmap.getHeight();}};}@Overridepublic Bitmap getBitmap(String url) {return mCache.get(url);}@Overridepublic void putBitmap(String url, Bitmap bitmap) {mCache.put(url, bitmap);}}
As you can see, here we set the size of the cached image to 10 MB. Modify the code for creating an ImageLoader instance. The second parameter is used to input the BitmapCache instance, as shown below:
ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
In this way, the functional advantages of ImageLoader are fully utilized.

3. NetworkImageView usage

In addition to the above two methods, Volley also provides the third method to load network images, that is, using NetworkImageView. Different from the preceding two methods, NetworkImageView is a custom control that inherits from ImageView and has all the functions of the ImageView control, in addition, the native network image loading function is added. The NetworkImageView control is easier to use than the previous two methods. It can be roughly divided into the following five steps:

1. Create a RequestQueue object.

2. Create an ImageLoader object.

3. Add a NetworkImageView control to the layout file.

4. Obtain the control instance in the code.

5. Set the image address to be loaded.

The usage of step 1 and Step 2 is the same as that of ImageLoader, so we will start from step 3. First, modify the code in the layout file and add the NetworkImageView control to it, as shown below:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Send Request" />        <com.android.volley.toolbox.NetworkImageView         android:id="@+id/network_image_view"        android:layout_width="200dp"        android:layout_height="200dp"        android:layout_gravity="center_horizontal"        /></LinearLayout>
Then, the Activity obtains the instance of the control, which is very simple. The Code is as follows:
networkImageView = (NetworkImageView) findViewById(R.id.network_image_view);
After obtaining the NetworkImageView control instance, we can call its setDefaultImageResId () method, setErrorImageResId () method, and setImageUrl () method to set the images displayed during loading respectively, the image displayed when loading fails and the URL of the target image are as follows:
networkImageView.setDefaultImageResId(R.drawable.default_image);networkImageView.setErrorImageResId(R.drawable.failed_image);networkImageView.setImageUrl("http://img.my.csdn.net/uploads/201404/13/1397393290_5765.jpeg",imageLoader);
The setImageUrl () method receives two parameters. The first parameter is used to specify the image URL address, and the second parameter is the previously created ImageLoader object.

Well, it's that simple. Now run the program again, and you will see the same effect as loading Images Using ImageLoader. I will stop here.

Some may ask, either ImageRequest or ImageLoader can be used to load the network image, and a parameter of the maximum width and height can be input to compress the image, networkImageView does not provide a method to set the maximum width and height. Is it true that images loaded using NetworkImageView will not be compressed?

In fact, this is not the case. NetworkImageView does not need to provide any methods to set the maximum width and height, and can also compress the loaded image. This is because NetworkImageView is a control. When loading an image, it automatically obtains its own width and height, compares the width of the network image, and determines whether to compress the image. That is to say, the compression process is completely automated internally, and we don't need to worry about it. NetworkImageView always presents us with a network image of just size, so it won't take up any more memory, this is also the most simple and easy to use NetworkImageView.

Of course, if you don't want to compress the image, it's actually quite easy. You just need to set the layout_width and layout_height of NetworkImageView to wrap_content in the layout file, in this way, NetworkImageView will display the original size of the image without any compression.

In this way, we have learned how to use Volley to load network images. Today's explanation ends. In the next article, I will show you more functions of Volley.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.