<Android> Volley 이미지 불러오기 예제

Android Volley ImageLoader

Volley uses ImageLoader to load images from network, and also to cache them into your Android phone’s in-memory cache by using the LruCache class. A good approach would be to use Android ImageLoader in a singleton pattern, as same cache should be used throughout the application. Also if used in a singleton pattern your cache would not be activity dependent. Hence whenever you close and open the activity, your images could be picked up from the cache, saving network requests. Now this brings up a question, how to make this volley singleton class? please have a look at the code below:

In the above class you may see that a CustomVolleyRequestQueue is set up which can return an object of ImageLoader. The class above also creates an ImageCache which works with normal volley cache, but only caching images for requests. Please note here: I just modified the singleton class from my previous Volley Example. Therefore as a whole, the above class can be used to make any type of Android volley requests, be it a JsonRequest, ImageRequest, or just a simple StringRequest.

Android Volley NetworkImageView

A new view introduced with Android volley is NetworkImageView. As a matter of fact this view replaces the standard ImageView, when comes to the usage of volley. Android Volley NetworkImageView is designed in such a way that it creates an image request, sends it and even displays the image, after it is downloaded from the URL. Also it cancels the request on its own if it is detached from the view hierarchy. Hence no need to handle the request cancellations with Volley NetworkImageView. Have a look at the layout for this Android Volley ImageLoader and NetworkImageView Example, it just includes a NetworkImageView instead of ImageView:

Next lets have a look at the code for the main activity class:

As you may see in the above class I used an instance of CustomVolleyRequestQueue to get the volley ImageLoader object. Further I just specified the URL through setImageUrl method of NetworkImageView. This handles all the functionality by itself.

Want to display images in a ListView using volley?

If you need to display images in a ListView just use the setImageUrl method of NetworkImageView in the getView method of your adapter. This will handle all your image requests automatically. Just a reminder, don’t forget to use the  NetworkImageView instead of normal ImageView.

Screenshot of Android Volley ImageLoader Example:
Android Volley NetworkImageView

 

 

 

 

 

출처:http://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/

+ Recent posts