One of the new concepts introduced in Android is Volley. The reason, volley library is preferred over other similar libraries is because it is authored by Google engineers. But one of the major problems with volley library is that it lacks proper documentation. As far as I know the only official documentation available is at this Android Developers page. Coming to the point, here I will discuss how to make an Android Volley ImageLoader Example using the NetworkImageView. As in one of my earlier tutorials, we discussed how to make asynchronous HTTP calls through Volley, I will not go in details of Volley. Volley is a highly customizable library and can be used in many situations like, displaying images in a ListView, RecyclerView, or just getting plain data from REST web APIs. Here we will discuss the basic building blocks of volley which may help you to retrieve images from the network.
To start off with volley first you may need to download and include Android volley library in your project. For steps please refer to this volley tutorial. Next you may need to add the internet permission in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
How to load images through Android Volley ImageLoader?
Earlier to load images in an Android ImageView, the standard approach taken was, the usage of HttpURLConnection
class. But now with volley this is simplified as we may not need to get in to such complex code. Volley gives us two new classes which make life easier.
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:
package com.truiton.volleyimageloader; import android.content.Context; import android.graphics.Bitmap; import android.util.LruCache; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; /** * Custom implementation of Volley Request Queue */ public class CustomVolleyRequestQueue { private static CustomVolleyRequestQueue mInstance; private static Context mCtx; private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private CustomVolleyRequestQueue(Context context) { mCtx = context; mRequestQueue = getRequestQueue(); mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() { private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20); @Override public Bitmap getBitmap(String url) { return cache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { cache.put(url, bitmap); } }); } public static synchronized CustomVolleyRequestQueue getInstance(Context context) { if (mInstance == null) { mInstance = new CustomVolleyRequestQueue(context); } return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024); Network network = new BasicNetwork(new HurlStack()); mRequestQueue = new RequestQueue(cache, network); // Don't forget to start the volley request queue mRequestQueue.start(); } return mRequestQueue; } public ImageLoader getImageLoader() { return mImageLoader; } }
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:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <com.android.volley.toolbox.NetworkImageView android:id="@+id/networkImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:background="#000000"/> </RelativeLayout>
Next lets have a look at the code for the main activity class:
package com.truiton.volleyimageloader; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; public class MainActivity extends AppCompatActivity { private NetworkImageView mNetworkImageView; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNetworkImageView = (NetworkImageView) findViewById(R.id .networkImageView); } @Override protected void onStart() { super.onStart(); // Instantiate the RequestQueue. mImageLoader = CustomVolleyRequestQueue.getInstance(this.getApplicationContext()) .getImageLoader(); //Image URL - This can point to any image file supported by Android final String url = "http://goo.gl/0rkaBz"; mImageLoader.get(url, ImageLoader.getImageListener(mNetworkImageView, R.mipmap.truiton_short, android.R.drawable .ic_dialog_alert)); mNetworkImageView.setImageUrl(url, mImageLoader); } }
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:
For better understanding, please refer to full source code below:
Default images in Android Volley NetworkImageView
There are situations when you may just want to simply display a placeholder for an image which is about to be fetched from the the network. With Android Volley ImageLoader this can be done very easily. It gives a get
method, through which you can display a default image as well as an error image in-case the request fails. In this ImageLoader tutorial I have used R.mipmap.truiton_short
as a default image and android.R.drawable.ic_dialog_alert
as an error image in the main activity class above. Hope this helped you. Please connect with us on Facebook, Google+, and Twitter for more updates.
Born in New Delhi, India. A software engineer by profession, an android enthusiast and an evangelist. My motive here is to create a group of skilled developers, who can develop something new and good. Reason being programming is my passion, and also it feels good to make a device do something you want. In a very short span of time professionally I have worked with many tech firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, and whenever I get spare time I share my thoughts here at Truiton.
Thanks to document. by Picasso we have some ability to display image such as : resize, centerCrop and create animation on onSuccess method. can we merge Volly and Picasso to have or create this ability?
please Notify me of new posts by email.
Mohit,
How to requestimage using Volley. I want to use volley When I capture image from camera and store it in server using PHP Code.
Can you help me on this?
This Volley Not Working In Eclipse Can You Explain More?
I Have Ubantu Linux O/S In Which I Have Eclipse Is = Android Developer Tools And Build: v22.6.2-1085508.
So How Can I Use Volley In My Project?
Nice tutorial. This works fine in my app. I have one question, in your code on CustomVolleyRequesQueue you use getBitmap and putBitmap . When we use Networked image we use internet and the url in order to cache the image. How you display the images without internet connection. If you downloaded once you have all images in cache.right? So, how you display these images from cache with just using the url. there is any way for this?
volley does it itself from cache.
Hi,
Thanks for the tutorial. This is not working for large size images. Can you please suggest me any idea?
Thanks a ton! It really helped me in displaying network images quickly and efficiently..
how to set auth headers to ImageLoader
Same Issue, can’t find where to add headers
Superb article. It worked like charm.
I am using volley to load JSON from server but everytime it fetches data from server. I want the data to be cached. Just like the ImageLoader.
U said we can use the same class to make a JSON request. Can u please help me a little on how to make a JSON request??
Thank You