Written by Chris Leversuch
Dec 17, 2014

Simple Android network requests

Chris explores how we set up network requests for Android

Simple Android network requests explored

Most of our apps require network requests to a server to either; download data required for the app to run, or to send data back to the server such as login requests. There are lots of ways of doing this, but one we like is to use a couple of Google libraries - Volley (for the network requests) and Gson (for the JSON parsing).

Volley

First we’ll look at Volley. You can add this to your project a couple of ways, either download the official source code and compile it into a jar file; or use the unofficial mirror that’s been uploaded to Maven Central. We’ll use the unofficial option because it’s quicker: just add the following to your app’s build.gradle file in the dependencies section:

compile 'com.mcxiaoke.volley:library:1.0.9@aar'

Volley uses request queues to hold the network requests, and provides a way of cancelling requests. For example if your Activity is being destroyed you could cancel any requests that the Activity has started. You can have as many request queues as you want but the simplest option is to just use one. We do this by creating a singleton class to hold the request queue:

public class NetworkManager {
    private static NetworkManager instance;
    private RequestQueue mRequestQueue;

    private NetworkManager(Context context) {
        mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
    }

    public static NetworkManager getInstance(Context context) {
        if (instance == null) {
            instance = new NetworkManager(context);
        }

        return instance;
    }
}

Make a request using Volley

Now we’re ready to make a request using Volley. There are a few built-in request types that you can use, or you can write your own one. There are JSON request types that return either a JSON object or array, however we’ll use the string request type as we’ll do our own JSON parsing later using Gson.

A StringRequest takes a URL string, a response listener and an error listener. An example request method would be:

public void getMyObject() {
            Response.Listener listener = new Response.Listener() {
            @Override
            public void onResponse(String string) {

            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        };

        StringRequest request = new StringRequest("http://api.domain.com/my-object.json", listener, errorListener);
        mRequestQueue.add(request);
}

This would make a network request and either call onResponse with the JSON string or onErrorResponse with an error object.

Cancelling requests

We previously mentioned cancelling requests. This is done by giving requests a tag and then telling the request queue to cancel any requests with a specific tag. We’ll modify our getMyObject() method to take a tag parameter then add a cancel method:

public void getMyObject(Object tag) {
        Response.Listener listener = new Response.Listener() {
            @Override
            public void onResponse(String string) {

            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        };

        StringRequest request = new StringRequest("http://api.domain.com/my-object.json", listener, errorListener);
        request.setTag(tag);
        mRequestQueue.add(request);
}

public void cancelAll(Object tag) {
    mRequestQueue.cancelAll(tag);
}

Each Activity, Fragment, Object etc can now define its own tag then call NetworkManager.getInstance(this).cancel(TAG); for example in the Activity onDestroy() method.

Volley training

The official Volley training can be found here if you want to explore other options, including customising the RequestQueue with caching or different HTTP clients.

Gson

We’ll now move on to Gson. Our code so far gets a JSON string then does nothing with it. First we’ll add Gson to our project then we’ll look at how to use it. Similar to Volley, add the following line to your project’s build.gradle file in the dependencies section:

compile 'com.google.code.gson:gson:2.3.1'

Create Java classes

While you can use Gson to parse your JSON string in to generic JSON objects and arrays, we prefer to create Java classes to represent the JSON objects and use Gson to convert the JSON string into these classes. The classes then act as a kind of documentation that shows what information is available. We haven’t used any specific examples yet and we haven’t got any valid JSON so for now we’ll just create a Person class for this blog post but you’ll obviously need to customise this for your own needs:

public class Person {
    private String firstName;

    private String lastName;

    private String emailAddress;

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getEmailAddress() {
        return emailAddress;
    }
}

We now need to annotate this class with the JSON property names so that Gson knows how the JSON maps to the class:

public class Person {
    @SerializedName("FirstName")
    private String firstName;

    @SerializedName("LastName")
    private String lastName;

    @SerializedName("EmailAddress")
    private String emailAddress;

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getEmailAddress() {
        return emailAddress;
    }
}

This means that the FirstName property in the JSON will be mapped to the firstName property in the class. We can now go back to our Volley response listener and add some code to our onResponse() method:

public void onResponse(String string) {
        Person person = new Gson().fromJson(string, Person.class);
}

This now gives us a person object that we can use. The next step is out of the scope of this post but we suggest you look at something like the EventBus library for sending the person object to any object that needs it. As a quick extension to the code above, if you actually had an array of Person objects in your JSON string, you could simply do:

Person[] person = new Gson().fromJson(string, Person[].class);

Download the sample project

Top