HTTP networking on Android using Volley

One of the most common functionalities that as Android developers we need to implement is the network communication. Almost all apps at some point needs to get some kind of data from a server, web service, etc.

We could implement our own classes using for example the Java HttpURLConnection, but as pragmatic, productive and lazy developers we should always try to don’t reinvent the wheel and find some reliable and well tested library.

Two of the best and more used options are Retrofit from the Square people and Volley from Google, which I’m going to focus in this post and I will leave Retrofit for another post.

 

What is Volley?

Volley is a library created by Google that offers out of the box a set of very cool features, amongst others :

  • Concurrent connections.
  • Automatic requests scheduling and cancelation.
  • Memory and disk response caching.

Here you can find a good talk at the 2013 Google I/O conference from Ficus Kirkpatrick:

 

Integration in our project

So, let’s see how to use it. First thing we have to clone the project from Git:
https://android.googlesource.com/platform/frameworks/volley

and then import it in our project or make a .jar and include it as a library.

Probably our app will be making requests in different activities quite often so the most optimum way to manage the life of our Volley object is implementing a Singleton class and create the instance it on the Application class instead or creating a new object on each activity. This singleton is going to contain the RequestQueue object that will manage the requests concurrency. Something like this:

    private static VolleyManager mInstance = null;
    private static Context mContext;
    private RequestQueue mRequestQueue;

    private VolleyManager(Context context) {
        mContext = context;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized VolleyManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleyManager(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

 

HTTP GET

Now we are going to implement a simple HTTP GET request that will retrieve a Json object. Volley offers four types of requests responses: “StringRequest”, “ImageRequest”, “JsonObjectRequest” and finally the ability to implement our custom request.

In this example we will be using a JsonObjectRequest. It’s based on real code from our public transport app BilbaoMoves, where we are calling to our server to get the real time arrivals of a specific transport stop. I just changed the endpoint url and the classes names.

It looks like this:

	JsonObjectRequest jsObjRequest =
        new JsonObjectRequest(Request.Method.GET, "http://urlToAnAwesomeEndpoint/webservice/",
                null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject jsonObject) {

				Gson gson = new Gson();

                MyExampleClass myExample =
                    gson.fromJson(jsonObject.toString(), MyExampleClass.class);

				//	Do something awesome here with myExample object
				//	.......

           }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            	//	The request failed  😦
            }
        });

        // Access the RequestQueue through the singleton class.
        mVolleyMng.addToRequestQueue(jsObjRequest);

 

HTTP POST

Creating a HTTP POST and send parameters in the request is quite straightforward as you can see in this example:

ExampleClass exampleObj = new ExampleClass();
exampleObj.setName("David");
exampleObj.setSurname("Guerrero");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(exampleObj),
     new Response.Listener<JSONObject>() {
         @Override
         public void onResponse(JSONObject response) {
             try {
                  //   Everything went OK
             } catch (JSONException e) {
                 e.printStackTrace();
             }
         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
              //   Hmmm... Something went wrong
         }
 });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

</pre>
<pre>

 

Cancel a Request

Sometimes we will need to cancel a request, for example when the user close the app or change to a different activity where we don’t need any more the data provided by the request. We could place the cancel request code in the onStop event of our activity, something like this:


@Override
protected void onStop () {
    super.onStop();
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(TAG);
    }
}

 

And that’s all. This is a basic introduction to how to make basic requests, but Volley offer another really interesting and useful features like caching and image loader (eg. to populate a list view with images asynchronously), but that will be material for another post. Until then, please all comments, suggestions and questions are very welcome!

 

Advertisements
Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: