Android Volley Tutorial

Volley is an android library released by Google that can make your life easier when dealing with network operations. In this blog post I will mention the main features of the library and show a few example usages, in particular, how to make a request, how to download images, and how to use the cache.

Features of Volley library

a) Automatically schedules the network requests

b) Supports request prioritization. This means that you can load content depending of priorities, for example the main content could have a high priority, but the images a low priority.

c) Provides transparent disk and memory cache that allows for quick reloading of data. Transparent cache means that the caller doesn’t have to know about the existence of the cache. That is, the cache is implemented automatically. You do, however, have the possibility to disable the caching.

d) Provides a good API for canceling requests. You can cancel a single request, or cancel requests depending on some filters.

Besides the great features that Volley comes with, you don’t have to use it for everything. Volley is great for RPC-style network operations that populate UI, a typical example would be loading thumbnail images into a ListView, but not very good for streaming operations like downloading a video or mp3.

Getting started with Volley

1. Clone the Volley project:
git clone
2. Import the library into your project

The most frequent classes of Volley that you will work with are RequestQueue and Request, and ImageLoader when dealing with images loading.

RequestQueue is used for dispatching requests to the network. It is recommended to create it early and use it as a Singleton.
Request is the base class for creating network requests (GET, POST).
ImageLoader is a helper class that handles loading and caching images from remote URLs.

Step 1:

As recommended, lets create first a Singleton class that will return on demand an instance of RequestQueue and one of ImageLoader.

public class VolleySingleton {

    private static VolleySingleton instance;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    private VolleySingleton(Context context) {
        requestQueue = Volley.newRequestQueue(context);

        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);

            public Bitmap getBitmap(String url) {
                return cache.get(url);

            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);

    public static VolleySingleton getInstance(Context context) {
        if (instance == null) {
            instance = new VolleySingleton(context);
        return instance;

    public RequestQueue getRequestQueue() {
        return requestQueue;

    public ImageLoader getImageLoader() {
        return imageLoader;
Step 2: Add internet permission
<uses-permission android:name="android.permission.INTERNET" /> 
Step 3: Create an instance of RequestQueue
RequestQueue queue = VolleySingleton.getInstance(this).getRequestQueue();
Step 4: Create the request

Volley comes with a class called JsonRequest that you can use to make requests to a server that returns a json response.
However, in this example we will query an RSS feed which returns a response in XML format. Volley does not include a similar class for handling xml responses, like JsonRequest, but it has StringRequest class that can be used to retrieve the response body as a String.

There are two ways to construct a StringRequest:

StringRequest(int method, String url, Listener<String> listener,
            ErrorListener errorListener)


StringRequest(String url, Listener<String> listener, ErrorListener errorListener)

The second constructor does not take the request method as a parameter, when not specified, a GET request is created.

Listener is a callback interface for delivering the result, and
ErrorListener is a callback interface for delivering error responses.


String url = "";
StringRequest request = new StringRequest(url, new Listener<String>() {

            public void onResponse(String response) {
                // we got the response, now our job is to handle it 
        }, new ErrorListener() {

            public void onErrorResponse(VolleyError error) {
               //something happened, treat the error.
Step 6: Execute the request

And that is all! The execution of the request implies its addition to the RequestQueue.

Step 7: Loading thumbnail images

Loading images can be done easy if you replace the android’s ImageView with Volley’s NetworkImageView:

        android:src="@drawable/default_placeholder" />

then use setImageUrl() and you are done!

String url = "..."; // URL of the image
ImageView imageView = (ImageView)view.findViewById(;
ImageLoader imageLoader = VolleySingleton.getImageLoader(); 
imageView.setImageUrl(url, imageLoader); 

If, for some reason, you don’t want or can’t use NetworkImageView, then there’s an alternate method.
You can use the get() method of ImageLoader class which accepts the image url and an instance of ImageListener:

ImageLoader imageLoader = VolleySingleton.getImageLoader(); 
imageLoader.get(url, new ImageListener() {
            public void onErrorResponse(VolleyError error) {
                imageView.setImageResource(R.drawable.icon_error); // set an error image if the download fails
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {
Reading from cache

One of the Volley’s features is that it provides transparent disk and memory cache. The cache is implemented automatically for classes that extends Request, such as JsonRequest and StringRequest.

To read the cache:

Entry entry = queue.getCache().get(url);
     String data = new String(, "UTF-8");
     // process data

To turn off the cache:


to remove the cache for a specific request:


to clear all cache:


to invalidate the cache: this will allow to display the cached data until the response is received. When the response is received, it will automatically override the cached data.

queue.getCache().invalidate(url, true);

For more details about Volley you can watch the full video at:

Caching Objects in Android Internal Storage

Android provides several options for persisting application data, such as SQLite Databases, SharedPreferences, internal and external storage.

In this post we’ll take a look how we can use the internal storage to persist application data. By default, files saved to internal storage are private to the application and they cannot be accessed by other applications. When the application is uninstalled, the files are removed.

To create and write a file to internal storage, openFileInput(); should be used. This opens a private file associated with the Context’s application package for writing. If the file does not already exits, then it is first created.

openFileInput() returns a FileInputStream, and we could use its write() method, which accepts a byte array as argument, to write the data. However, in the below example we will wrap the FileInputStream into an ObjectOutputStream which provides 2 convenient methodsĀ  for writing and reading objects: writeObject() and readObject().

So, letsĀ  pretend that we need to save a List of some objects. The model class of our object looks like this:

public class Entry implements Serializable{
   private String name;

   public Entry(String name) { = name;

   public String getName() {
      return name;

Make sure that the model class implements Serializable, otherwise you may get a when attempting to write the object on internal storage.

Below is the utility class that provides 2 methods, one for storing objects to internal storage, and another for retrieving objects from internal storage.

public final class InternalStorage{

   private InternalStorage() {}

   public static void writeObject(Context context, String key, Object object) throws IOException {
      FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE);
      ObjectOutputStream oos = new ObjectOutputStream(fos);

   public static Object readObject(Context context, String key) throws IOException,
         ClassNotFoundException {
      FileInputStream fis = context.openFileInput(key);
      ObjectInputStream ois = new ObjectInputStream(fis);
      Object object = ois.readObject();
      return object;

An this is how InternalStorage class can be used to persist and retrieve data from internal storage.

// The list that should be saved to internal storage.
List<Entry> entries = new ArrayList<Entry>();
entries.add(new Entry("House"));
entries.add(new Entry("Car"));
entries.add(new Entry("Job"));

try {
   // Save the list of entries to internal storage
   InternalStorage.writeObject(this, KEY, entries);

   // Retrieve the list from internal storage
   List<Entry> cachedEntries = (List<Entry>) InternalStorage.readObject(this, KEY);

   // Display the items from the list retrieved.
   for (Entry entry : cachedEntries) {
     Log.d(TAG, entry.getName());
} catch (IOException e) {
   Log.e(TAG, e.getMessage());
} catch (ClassNotFoundException e) {
   Log.e(TAG, e.getMessage());