Android volley tutorial

Android Volley is used to manage HTTP connections in your Android app. Follow this tutorial to know how to post data and download images

This Android Volley Tutorial describes how to use Android Volley library. Android Volley is an Google library that helps developers to build HTTP clients in Android. This library handles HTTTP request and response. This library simplifies the Android app development.
In the previous post, we talked about HttpUrlConnection  It is valid and useful but using Volley we can simplify our work.

To use Android Volley in your Android project,  it is necessary to add it using gradle:

dependencies {
  ...
  compile 'com.android.volley:volley:1.1.0'
}

Alternatively, Android Volley is a library that can be downloaded from git using:

git clone https://android.googlesource.com/platform/frameworks/volley

Once we get the code, we can build up our project. If you notice the code you download is meant for Android Studio. Don’t forget to set the project as library.or you can add it to your project using gradle.

You can download the project code from here:

Why use Volley in Android?

We may ask why we need to use another library if we have already everything we need to handle network connection (i.e Http connection). Well, if you read the previous posts, you notice we have some work to do. For example, we have to create an AsyncTask, handle the network connection errors and so on. Volley simplifies the development process and increases the app performances. The main features provided by Volley are:

  • Efficient network management
  • Easy to use request management
  • Disk and memory cache management
  • Easy to extend and customize to our needs

These points are enough to choose Android Volley as our base networking library. In this post, I will show some basic operations with Volley while in some other posts I will show some other more “complex” operation.

Android Volley core

When we use Android Volley there are some classes that play an important role. They are the classes we will use more often. These classes handle:

  • RequestQueue
  • Android Http Request
  • Android Http Response

RequestQueue is the core class of Android Volley lib. It manages all the requests we make in our app. It takes care of queuing the requests and handle the responses. Usually, we create an instance of this class calling:

RequestQueue rq = Volley.newRequestQueue(this);

This code line creates a RequestQueue instance with default parameters. If we want to have more control, we can instantiate this class directly. Once we have our request queue instance, we can add our requests. Network requests are instances of Request class. Usually, we have everything we need under the toolbox package, but we can always customize our request extending Request class and providing our logic. Response class is the class we use when we want to listen to the response data or to the error events.
We will see it in more detail later. If we don’t have special needs, we can use some classes in the toolbox package. These classes help us handling common requests: string request and image request for example.

How to make an HTTP Post request in Android Volley

One of the most common requests we usually make is the HTTP POST request. With this HTTP method, we send a payload containing some information according to the server specification. In this scenario, we can use a StringRequest, because we expect to send a payload that is a String and receive a String as the response. So we have:

RequestQueue rq = Volley.newRequestQueue(this);
StringRequest postReq = new StringRequest(Request.Method.POST, 
                             "http://httpbin.org/post", 
  new Response.Listener<String>() {
      @Override
      public void onResponse(String response) {
         // We set the response data in the TextView
         tv.setText(response); 
      }
  }, 
  new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
      System.out.println("Error ["+error+"]");
      // handle the error here
   }
}) ;

At line 1, we create a request queue handler. At line 2, we instantiate the StringRequest. You can notice that the code seems a bit too complex, but it is very simple. The first thing we specify that this request is a POST request, then the destination URL (http://httpbin.org).  Looking at the code, you can notice we have two different listeners:

  • Response.Listener
  • Response.ErrorListener

The first one is called when the response is received and is ready. In this case the onResponse method is called. This method runs in the main thread so we can update, for example, some UI widgets. If something goes wrong, the ErrorListener.onErrorResponse is called. In this method, we have the chance to handle the error and notify it to the user.

Until now, we didn’t send any parameter. If we want to post some data to a remote server we have to override getParams method. In the Request class, getParams is a method that returns null. If we want to post some params, we have to return a Map with key-value pair. In this case, we can override this method:

RequestQueue rq = Volley.newRequestQueue(this);
StringRequest postReq = new StringRequest(.....) {
   @Override
   protected Map<String, String> getParams() 
          throws AuthFailureError {
            Map<String, String> params = 
               new HashMap<String, String>();
      // param1 is the name of the parameter and param its value
      params.put("param1", param);  
      return params;
  }
};

In this case, we create a key called param1 and pass the value stored in param parameter. At the end, we need to add our request to the request queue.

rq.add(postReq);

Running the code, we have:
android volley post

How to download binary file – Download Image using Android Volley

What about if we want to download binary data? Well if we want to download an image from a remote server, we can use the ImageRequest. In this case, we have:

ImageRequest ir = new ImageRequest(url, 
    new Response.Listener<Bitmap>() {
      @Override
      public void onResponse(Bitmap response) {
         iv.setImageBitmap(response);
      }
}, 0, 0, null, null);

As before, in the onResponse method, we set the image we receive from the remote server (line 4). We could set the image width and height and other parameters. In this case, we didn’t implement the error listener. In this case, we have:

android volley download image

 

How to make a Custom request in Android Volley

As said, we can extend the base Request class, so that we can implement our logic. In this case, we to override two methods:

  • parseNetworkResponse
  • deliverResponse

In the first method, we have to extract the data from the response while in the other one we notify the response. We will cover these aspects in some other posts.

22 COMMENTS

  1. Love the tutorial, but you say at the end: "Source code available soon."
    /* please define..when is the date/time for: "soon" : (
    I (and I'm sure others) would love to have this as full project as a downloadable zip!
    –what code are you using to print (output) to the the activity view?
    –is there a textview involved?
    –what is the .xml file for the layout of this app?

  2. Hi, I want to post without response to a URL that opens a new view please how can I achieve this. Similar to setting action in a html form and clicking submit button.

    • Try this:
      public void getImage(String url, final Listener listener) {
      ImageRequest ir = new ImageRequest(url, new Response.Listener() {

      @Override
      public void onResponse(Bitmap response) {
      if (listener != null)
      listener.onImageReady(response);
      }
      }, 0, 0, null, null);

      queue.add(ir);
      }

  3. i have gone through so many websites and video tutorials,but i didn’t get any idea about volley library.But after watching your tutorial i got the exact idea about Volley.thank you for your great information towards the volley.I am expecting knowledge for rest of the topics also.

LEAVE A REPLY

Please enter your comment!
Please enter your name here