Volley for Network Calls - Part 1

GOOGLE IO 2013

Watch the Google IO 2013 video on Volley.

Volley is a networking library, introduced in Google IO 2013 which is basically used to make network calls. Volley is extremely useful in case such as accessing JSON API, loading images using ImageLoader etc.

In the previous post, I gave an introduction on why to use volley in place of AsyncTask/HttpURLConnection for making network calls.

NOTE : Volley should be used only to query network server, not to download any bigger file such as mp3 files etc.

How to Install ?

Add a single line of dependency to your gradle file:

compile 'com.android.volley:volley:1.0.0'

And, Make sure to add INTERNET permission to the manifest file, since we are accessing internet for quering data.

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

How to Use ?

private RequestQueue requestQueue;

public RequestQueue getRequestQueue() {
    if (requestQueue == null) {
        requestQueue = Volley.newRequestQueue(this);
    }
    return requestQueue;
}

Using this method, you will be able to get the request queue for making network calls.

//url for getting JSON data
String url = "http://jsonplaceholder.typicode.com/posts";

//creating a json array request for making a call
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
    @Override
    public void onResponse(JSONArray response) {
        Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_LONG).show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

    }
});

//get the request queue from your Application class (you will need to typecast it to your Custom Application), and the json request to the queue.
((DemoApplication) getApplication()).getRequestQueue().add(jsonArrayRequest);

This is how we fetch the JSON Data from the server, this remains similar incase of JSONObjectRequest(to get json object) and StringRequest (to get string format data from the server).

Features ?

This was a very basic explanation on why to use volley instead of HttpURLConnection for making network calls and how to use it. In the next part I will have a more deep discussion on volley library, and how to load images using volley.

Stay Tuned!