Mobile
Article

Volley, a Networking Library for Android

By Valdio Veliu

Volley, a networking library for Android

Most apps need network access to send and receive data, which is a complex task. Until HoneyComb, network calls ran from the main thread and in subsequent Android versions, network requests executed asynchronously from the main thread. To make a network call, a developer needs to implement an Asynctask in a different thread from the main application thread or a NetworkOnMainThreadException will be thrown.

Volley to the Rescue

Volley will help avoid all this frustrating work.

Volley is a library for Android that manages network requests. It bundles the most important features you’ll need such as accessing JSON APIs, loading images and String requests in an easier-to-use package.

Designed for RPC (Remote Procedure Call) network operations, Volley is perfect for populating UI elements. It’s not for streaming operations like downloading a video or a MP3.

In your application code, you create a Volley Request, queue it on the main thread and receive responses. The work happens on the main thread and this aspect of Volley is perfect for populating the UI of any app because you can’t touch the UI from a background thread.

Importing Volley

Import the library from a Mirror by adding the following in the gradle dependencies:

dependencies {
   ...
compile 'com.mcxiaoke.volley:library:1.0.19'
}

This will get you started right away, but I don’t recommend it because it’s not an official Volley repository.

I like to use the official Volley source and suggest you clone its repo and add the folder to the Android project as a module (File -> Import Module).

Open settings.gradle and check that the below is in the file.

include ':app', ':volley'

Open build.gradle and add the dependency:

dependencies {
   ...
compile project(":volley")
}

Sync Gradle and you are all set.

Developing with Volley

Now I will go into detail about using Volley to make some standard network requests.

In the manifest file add the following INTERNET permission:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Volley handles network communication managed by a RequestQueue. To make network requests, initialize a queue in the MainActivity class and all requests will be added to this queue.

RequestQueue queue = Volley.newRequestQueue(this);

The three core functions of Volley are loading images and making String and JSON requests.

Json Requests

Volley has Requests for JSONObject and JSONArray. The structure of JSONRequest and most of the request classes included in Volley use constructors like the following.

JsonObjectRequest request JsonObjectRequest(RequestMethod, URL, null,  new ResponseListener(), new ErrorListener());

The parameters passed into the constructor:

  • RequestMethod (GET, POST, PUT, DELETE, etc.)
  • URL: String of the URL of the required object
  • JSONObject: An optional object posted with the request, null if there is no object posted
  • ResponseListener: Response Listener, whose callback method will contain the response
  • ErrorListener: A Response.ErrorListener whose callback method will contain any problem with the request.
/*Json Request*/
       String url = "https://json_url/";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(  Request.Method.GET, url, null,
     new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   Toast.makeText(MainActivity.this, response.toString(),Toast.LENGTH_SHORT).show();
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       },
               new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {

           }
       });
 //add request to queue
queue.add(jsonObjectRequest);

The same structure applies to JsonArrayRequest, but with a return response of a JsonArray.

Now that I’ve shown how to receive JSON data in Android, let’s see how to post data with Volley.

The request is the same format as receiving JSON data with the exception that you must specify a JSONObject posted with the request and request headers for sending data from the client to server side.

    /*Post data*/
    Map<String, String> jsonParams = new HashMap<String, String>();

jsonParams.put("email", "user@gmail.com");
jsonParams.put("username", "user");
jsonParams.put("password", "pass");

    JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, URL,

          new JSONObject(jsonParams),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                  //   Handle Error
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("User-agent", System.getProperty("http.agent"));
            return headers;
        }
    };
queue.add(postRequest);

This request worked for me, but the request headers might have to change depending on the development use case.

Image Request

Volley isn’t an image loading library, it’s an asynchronous networking library, but offers basic image handling requests. The following code is an example of an ImageRequest to load an image into an ImageView.

String URL= "http://image_url.png";
   ImageRequest imageRequest = new ImageRequest(URL, new Response.Listener<Bitmap>() {
           @Override
           public void onResponse(Bitmap response) {
               // Assign the response to an ImageView
               ImageView imageView = (ImageView) findViewById(R.id.imageView);
               imageView.setImageBitmap(response);
           }
       }, int maxWidth, int maxHeight, null, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
              Log.d(TAG , error.toString());
           }
       });
    //add request to queue
    queue.add(imageRequest);

The structure of the ImageRequest is straightforward. All it needs is the image’s URL, a Response Listener, whose callback method will contain the image Bitmap as a response, a maxWidth and maxHeight, a Config format to decode the bitmap to and a Response.ErrorListener for any response errors. Add the request to the RequestQueue and the Android runtime will handle the rest.

String Request

This type of request is used to retrieve data from a server as a String. For example to retrieve XML, the drawback is that you have to do the parsing of the String yourself.

String URL = "http://string_url/";
       StringRequest stringReq = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
           @Override
           public void onResponse(String response) {

              // Assign the response to an TextView
              TextView tv = (TextView)findViewById(R.id.textView);
               tv.setText(response);
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
              Log.d(TAG , error.toString());
           }
       }) ;
     //add request to queue
    queue.add(stringReq);

The structure of the StringRequest contains a request method (POST or GET), a URL to the String source, a Response.Listener and a Response.ErrorListener. Pretty much the same as the JsonRequest.

Request Prioritization

Handling network requests means prioritizing what’s needed and how fast the response is needed, since networking is a real time operation.

Volley processes the requests from higher priorities to lower priorities, in first-in-first-out order. There is no setPriority() method, so to prioritize a request, some work is needed.

Here is an example of a custom JSONRequest class that can make priority requests. The focus of this class is on the overridden getPriority() method. When the request is added to the queue this method will return the priority assigned to it by setPriority(), or will return Priority.HIGH assigned inside the class, but it won’t search for a priority outside this class.

The same structure applies to all the other request types.

public class CustomPriorityRequest extends JsonObjectRequest {

    Priority priority = Priority.HIGH;

    public CustomPriorityRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
    }

    public CustomPriorityRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(url, jsonRequest, listener, errorListener);
    }

    @Override
    public Priority getPriority() {
        return priority;
    }

    public void setPriority(Priority p){
        priority = p;
    }
}

Making a request with this new class is the same as the standard requests. You have the ability to set a request priority before adding it to the queue.

CustomPriorityRequest customRequest = new CustomPriorityRequest(
        Request.Method.GET, URL, null,
        new Response.Listener<JSONObject>(),
        new Response.ErrorListener());

customPriorityRequest.setPriority(Request.Priority.IMMEDIATE);
queue.add(customPriorityRequest);

Some available priorities are: Priority.LOW, Priority.NORMAL, Priority.HIGH and Priority.IMMEDIATE.

Cancel Requests

Another useful tool in Volley is the ability to cancel the requests. Canceling requests is useful when the user closes the app or performs an action that results in not using the responses of the Volley requests. There is no sense executing the remaining requests in the queue, so we cancel them in the onStop() method.

The easiest way to cancel requests in Volley is to add a tag to the request and when the queued requests need to be canceled, call the cancelAll() method. This will cancel all the requests specified with that specific tag.

request.setTag("TAG");

queue.cancelAll("TAG");

Once cancelAll() executes from the main thread, the remaining responses will not be delivered.

Conclusion

Volley is an essential tool in Android development, reducing the hard work needed to just a few lines of code. What experiences have you had with Volley?

  • Aleksander Koko

    If you add Otto (event bus) on the list than it can be even cooler :)

    • http://aziflaj.github.io/ Aldo Ziflaj

      Try RxAndroid with that and see which one is cooler :D

      • Aleksander Koko

        Had just a quick look on it, but Otto is simpler I think. Just a Singleton and ready to go.

      • Aleksander Koko

        Had just a quick look on it, but Otto is simpler I think. Just a Singleton and ready to go.

  • Valdio Veliu

    Thank you for your opinion .

    I thinks it is a matter of preference which of this
    networking libraries you use. They all are great, I’ve tried them.

    Sure Picasso is great and I have to say it’s better than
    Volley in the handling images, after all Picasso is totally focused on image
    loading.

    In my opinion the advantage of Volley is that Volley tries
    to solve a more general problem. Sure it’s more complex to use than the others
    but it is a very powerful tool.

  • http://www.mobileapptelligence.com/ kailash mobileapptelligence

    Top apps can’t be developed newcomers. They may code it but can’t build enterprise ready app. You must find a company with more than 5 years of experience in developing the business apps. In India, top android app development companies are delivering next in class apps to global clients. Mobileapptelligence [dot] com, an award winning Android app development company, is delivering best in class Android apps to global clients.

  • Ashish Singh

    Can you share some ideas, How to send the image on server using volley ?

  • Frank Arkhurst Odoom

    how do u check network response and open another intent i always get cannot convert string to jsonObject error

    • Valdio Veliu

      Probably the response you receive is not in JSON format … Check if the API you make the call to returns JSON.

  • amir mohsenian

    Hi , i can’t download String with 2G or 3G internet in volley . please help me

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Mobile, once a week, for free.