Android : Volley and Gson tutorial

Android Volley is the new way to make network requests. It has a lot of advantages : configurable thread pool, request priority, caching, request cancel. AsyncTask is no more needed and this is a good new as AsyncTask is known for its memory leak issues. In this quick step tutorial, i show the piece of source code to make it work with google gson library.


Test before
If you wish to test before, you can install the application with the following link. The whole source code of the project is also available on github. The airport screen use the volley library.

logo-app
Your app idea
Michenux
Free   
pulsante-google-play-store
pulsante-appbrain
qrcode-app

Prerequisite

At this time, there is no release of volley library so you have to download the source code and copy it inside your project.

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

In the activity

Declare a new attribute of type RequestQueue :

private RequestQueue requestQueue;

In the onCreate method, initialize the RequestCode and let’s call our startRequest method :

this.requestQueue = Volley.newRequestQueue(this.getActivity());
startRequest()

This is my startRequest method. I first instantiate a GsonRequest with the http get method, the url of the rest service, the value bean for mapping the json response, one listener for success and another for error. Finally, we add the request to the queue.

private void startRequest() {
    GsonRequest<MyRestResponse> jsObjRequest = new GsonRequest<MyRestResponse>(
        Method.GET,
        getString(R.string.rest_url),
        MyRestResponse.class, null,
        this.createRequestSuccessListener(),
        this.createRequestErrorListener());
    this.requestQueue.add(jsObjRequest);
}

Below the method to create the success listener. the onResponse method will be invoked on success. In that method, depending on your needs, you may for example update the adapter of your list.

private Response.Listener<MyRestResponse> createSuccessListener() {
    return new Response.Listener<MyRestResponse>() {
        @Override
        public void onResponse(MyRestResponse response) {
        }
    };
}

Then, the method to create the error listener. In this example, i use the crouton library to display the error.

private Response.ErrorListener createErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Crouton.makeText(
                MyFragment.this.getActivity(),
                getString(R.string.error_retrievingdata),
                Style.ALERT).show();               
        }
    };
}

The onDestroy method cancels all requests of the queue.

@Override
public void onDestroy() {
    this.requestQueue.cancelAll(this);
    Crouton.cancelAllCroutons();
    super.onDestroy();
}

Gson stuff for Volley

This is the class to use Google Gson with volley. I took it from the web and i customized it to make it work with timestamp type.

public class GsonRequest<T> extends Request<T> {
   
    private final Gson gson ;
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Listener<T> listener;
   
    public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers,
            Listener<T> listener, ErrorListener errorListener) {
        super(method, url, errorListener);
       
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Timestamp.class, new TimestampDeserializer());
        this.gson = gsonBuilder.create();
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }
 
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }
 
    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }
 
    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(
                    gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

This is the timestamp serializer for Gson. This class is optional, take it only if you need it :

public class TimestampDeserializer implements JsonDeserializer<Timestamp> {

    public Timestamp deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
        long time = Long.parseLong(json.getAsString());
        return new Timestamp(time * 1000);
    }
}
Share Button

Comments

Leave a Reply