Android volley get started to mastery: Load network pictures with volley

Source: Internet
Author: User

In the previous article, we learned what volley is and how it is used in its basic usage. In this article we are about to learn more advanced usage of volley, how you have not read my previous article, it is recommended to first read the Android volley fully Parse (a), the basic usage of the first knowledge volley .

As mentioned in the previous article, volley is a framework that integrates the advantages of asynchttpclient and Universal-image-loader. As we all know, Universal-image-loader has a very powerful ability to load network images, while using volley, we can also achieve basic similar effects, and in performance is not inferior to Universal-image-loader, Let's take a concrete look at it.

1. Usage of imagerequest

We have already learned the usage of stringrequest and jsonrequest, and have summed up their usage in a very similar way, basically the following three steps:

1. Create a Requestqueue object.

2. Create a Request object.

3. Add the Request object to the Requestqueue.

Stringrequest and Jsonrequest are inherited from request, so their usage is similar. So needless to say, today we have to learn imagerequest, believe that you have guessed from the name, it is also inherited from request, so its usage is basically the same, first need to get to a Requestqueue object, you can call the following methods to obtain:

1 requestqueue mqueue = volley.newrequestqueue (context);

The next step is to go to the new Imagerequest object, and the code looks like this:

1Imagerequest imagerequest =NewImagerequest (2"Http://developer.android.com/images/home/aw_dac.png",  3         NewResponse.listener<bitmap>() {  4 @Override5              Public voidOnresponse (Bitmap response) {6 Imageview.setimagebitmap (response); 7             }  8}, 0, 0, config.rgb_565,NewResponse.errorlistener () {9 @OverrideTen              Public voidonerrorresponse (volleyerror error) { One Imageview.setimageresource (r.drawable.default_image);  A             }   -});

As you can see, the Imagerequest constructor receives six parameters, the first parameter is the URL address of the picture, and there is nothing to explain. The second parameter is a successful callback for the picture request, where we set the returned bitmap parameter to ImageView. The third and fourth parameters are used to specify the maximum allowable width and height of the picture, if the specified network picture width or height is greater than the maximum value here, the picture will be compressed, specified as 0, no matter how large the picture, will not be compressed. The fifth parameter is used to specify the color properties of the picture, and several constants under Bitmap.config can be used here, where argb_8888 can show the best color properties, each pixel occupies a size of 4 bytes, and rgb_565 indicates that each picture pixel occupies 2 bytes. The sixth parameter is a callback for the failed picture request, where we display a default picture in ImageView when the request fails.

Finally, add this Imagerequest object to the Requestqueue, as shown below:

1 mqueue.add (imagerequest);

Now if you run the program and try to make a network request, you'll soon see that the pictures on the network are displayed in ImageView, as shown in:

2. Usage of Imageloader

If you think imagerequest is very good, then I can only say that you are too easy to meet the ^_^. In fact, volley can do much more than ask for a picture of the web, and Imageloader is a good example. Imageloader can also be used to load pictures on the network, and its interior is also implemented using Imagerequest, but imageloader is significantly more efficient than imagerequest because it not only helps us to cache images, You can also filter out duplicate links to avoid sending requests repeatedly.

Since Imageloader is not inherited from request, its usage is different from what we have learned before, which can be summed up roughly in the following four steps:

1. Create a Requestqueue object.

2. Create a Imageloader object.

3. Get a Imagelistener object.

4. Call Imageloader's Get () method to load the picture on the network.

Let's follow this step and learn how to use Imageloader. First the first step to create the Requestqueue object we have written many times, I believe that we do not have to repeat the introduction, then start from the second step to learn it, a new Imageloader object, the code is as follows:

1Imageloader Imageloader =NewImageloader (Mqueue,NewImagecache () {2 @Override3      Public voidputbitmap (String URL, Bitmap Bitmap) {4     }  5   6 @Override7      PublicBitmap getbitmap (String url) {8         return NULL; 9     }  Ten});

As you can see, the Imageloader constructor receives two parameters, the first parameter is the Requestqueue object, the second argument is a Imagecache object, and here we first new an empty Imagecache implementation.

Next you need to get a Imagelistener object, the code looks like this:

1 Imagelistener listener = Imageloader.getimagelistener (imageView,  2         R.drawable.default_image, R.drawable.failed_image);

We can get to a Imagelistener object by calling Imageloader's Getimagelistener () method, and the Getimagelistener () method receives three parameters, The first parameter specifies the ImageView control that is used to display the picture, the second parameter specifies the picture that is displayed during the loading of the picture, and the third parameter specifies the picture to display if the picture fails to load.

Finally, call Imageloader's Get () method to load the picture, as shown in the following code:

1

The Get () method receives two parameters, the first parameter is the URL address of the picture, and the second parameter is the Imagelistener object that was just fetched. Of course, if you want to limit the size of a picture, you can also use the Get () method's overload to specify the maximum allowable width and height for the picture, as follows:

1 imageloader.get ("Http://img.my.csdn.net/uploads/201404/13/1397393290_5765.jpeg",  2                  Listener, 200, 200);  

Now run the program and start loading the image, you will see a default picture displayed in ImageView, and when the picture on the network is loaded, ImageView will automatically display the graph, as shown in the results.

Although now we have mastered the use of imageloader, but the advantages of the Imageloader just introduced have not been used. Why is it? Because the Imagecache object created here is an empty implementation, it does not function as a picture cache at all. In fact, writing a imagecache is also very simple, but if you want to write a very good performance imagecache, it is best to use the LRUCache features provided by Android, if you do not understand LRUCache, you can refer to my previous blog Android efficient loading large map, multi-graph solution, effectively avoid program Oom.

Here we create a new Bitmapcache and implement the Imagecache interface as follows:

1BitmapcacheImplementsImagecache {2   3     PrivateLrucache<string, bitmap>Mcache; 4   5      PublicBitmapcache () {6         intMaxSize = 10 * 1024 * 1024; 7Mcache =NewLrucache<string, bitmap>(maxSize) {8 @Override9             protected intsizeOf (String key, Bitmap Bitmap) {Ten                 returnBitmap.getrowbytes () *bitmap.getheight ();  One             }   A         };  -     }   -    the @Override -      PublicBitmap getbitmap (String url) { -         returnmcache.get (URL);  -     }   +    - @Override +      Public voidputbitmap (String URL, Bitmap Bitmap) { A mcache.put (URL, bitmap);  at     }   -    -}

As you can see, here we set the size of the cached image to 10M. Then modify the code that creates the Imageloader instance, and the second parameter passes to the instance of Bitmapcache as follows:

1 New New Bitmapcache ());  

In this way we will make full use of the functional advantages of Imageloader.

3. Usage of Networkimageview

In addition to the above two methods, volley also provides a third way to load the network picture, that is, the use of Networkimageview. Unlike the two above, Networkimageview is a custom control that inherits from the ImageView, has all the functions of the ImageView control, and adds the ability to load the network picture on top of the native base. Networkimageview controls are easier to use than the first two, and can be broadly divided into the following five steps:

1. Create a Requestqueue object.

2. Create a Imageloader object.

3. Add a Networkimageview control to the layout file.

4. Get an instance of the control in your code.

5. Set the image address to be loaded.

The first and second steps are exactly the same as Imageloader, so here we start with the third step. First modify the code in the layout file and add the Networkimageview control inside it, as shown below:

1<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"2Android:layout_width= "Fill_parent"3android:layout_height= "Fill_parent"4android:orientation= "Vertical" >5   6<Button7Android:id= "@+id/button"8Android:layout_width= "Wrap_content"9android:layout_height= "Wrap_content"Tenandroid:text= "Send Request"/> One        A<Com.android.volley.toolbox.NetworkImageView -Android:id= "@+id/network_image_view" -Android:layout_width= "200DP" theandroid:layout_height= "200DP" -Android:layout_gravity= "Center_horizontal" -/> -    +</LinearLayout>

Then the activity gets to the instance of the control, which is very simple, and the code looks like this:

1 networkimageview = (networkimageview) Findviewbyid (R.id.network_image_view);

After we get an instance of the Networkimageview control, we can call its Setdefaultimageresid () method, the Seterrorimageresid () method, and the Setimageurl () method to set the picture that is displayed in the load separately, the picture to display when the load fails, and the URL address of the destination picture, as follows:

1 Networkimageview.setdefaultimageresid (r.drawable.default_image);   2 Networkimageview.seterrorimageresid (r.drawable.failed_image);   3 networkimageview.setimageurl ("Http://img.my.csdn.net/uploads/201404/13/1397393290_5765.jpeg",   4                 Imageloader);  

where the Setimageurl () method receives two parameters, the first parameter specifies the URL address of the picture, and the second parameter is the Imageloader object created earlier.

Well, it's that simple, now rerun the program and you'll see and use Imageloader to load the image exactly the same, and here I am no longer.

Then some friends may ask, using imagerequest and Imageloader both ways to load the network picture, you can pass in a maximum width and height of the parameters to compress the picture, The Networkimageview does not provide a way to set the maximum width and height, then is not the use of Networkimageview to load the picture will not be compressed it?

In fact, this is not the case, Networkimageview does not need to provide any method of setting the maximum width and height can also compress the loaded picture. This is because Networkimageview is a control that automatically acquires its own width when loading a picture, then compares the width of the network image and then decides whether or not to compress the image. In other words, the compression process is fully automated in the internal, do not need our concern, Networkimageview will always present to us a size just good network pictures, will not occupy any bit of memory, this is networkimageview the most simple and easy to use.

Of course, if you do not want to compress the picture, in fact, it is very simple, just in the layout file to the Networkimageview Layout_width and Layout_height are set to wrap_content on it, This networkimageview will show the original size of the image without any compression.

So we put the use of volley to load the network image usage is finished, today's explanation is over, the next article I will take you to continue to explore the volley more features.

Android volley get started to mastery: Load network pictures with 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.