Skip to main content

Custom Volley-Gson request implementation

This page covers Volley-Gson integration and also Volley custom Request. We assume that, you are familiar with Volley and Gson.


Volley has some inbuilt request which you can use, if your response is a String, Image, or JSON, in that case, you don't need to implement a custom Request.  To use Gson with Volley, we need to implement a custom request.
To make a custom request, you need to perform following operation.
  1. Extend Request<T> class, where T is the type of parsed response or expected response.
  2. Implement the abstract methods parseNetworkResponse() and deliverResponse().

 parseNetworkResponse:

 A response contains parse response of a given type i.e Gson.


@Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data, HttpHeaderParser.parseCharset(response.headers));
            if (BuildConfig.IS_DEBUG)
                Log.d(TAG, "Response :: " + response.data == null ? null : new String(response.data));
            return Response.success(
                    mGson.fromJson(json, mClass), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException ex) {
            return Response.error(new ParseError(ex));
        } catch (JsonSyntaxException ex) {
            return Response.error(new ParseError(ex));
        }
    }


deliverResponse:

This is callback interface which Volley use to call back you on the main thread using the Object you returned in parseNetworkResponse().


@Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);
    }


Complete Code:

 public class GSONRequest<T> extends Request<T> {
    private static final String TAG = "
GSONRequest";
    private final Class<T> mClass;
    private final Response.Listener<T> mListener;
    private final Gson mGson = new Gson();

    /**
     * Make a POST request and return a parsed object from JSON.
     *
     * @param url           for request
     * @param tClass        Gson reflection class object
     * @param listener      responce listener
     * @param errorListener responce error listener
     */
    public GSONRequest(String url, Class<T> tClass,
                       Response.Listener<T> listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        mClass = tClass;
        mListener = listener;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        return super.getBody();
    }

    @Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data, HttpHeaderParser.parseCharset(response.headers));
            if (BuildConfig.IS_DEBUG)
                Log.d(TAG, "Response :: " + response.data == null ? null : new String(response.data));
            return Response.success(
                    mGson.fromJson(json, mClass), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException ex) {
            return Response.error(new ParseError(ex));
        } catch (JsonSyntaxException ex) {
            return Response.error(new ParseError(ex));
        }
    }
}

 
Source Code download

Comments

Popular posts from this blog

Display News and Videos through RSS and Display it in Listview

Hi friends , In this tutorial ,i'm going to describe about how to fetch data from rss feed.Here i had also problem ,when i was developing my recent project.I had also faced  many problem and at last i developed my best project. Here is the code that describe how to fetch news headline from rss This class describes how to parse XML data: import java.net.URL; import java.util.ArrayList; import org.xmlpull.v1.XmlPullParser; import android.content.res.XmlResourceParser; import android.util.Log; import android.util.Xml; public class XmlFeedParser {         //Feed Parsing Method     public ArrayList<Implement> parse(String url) {                 //Array of Episode Objects         ArrayList<Implement> episodes = null;          ...

Android O New Features Overview

This post assumes, you are an experienced developer who wants to get started with the latest version of Android. Android O is not a huge update to the OS and application framework like M but it still has many useful features for both developer and an user. Android O has focus on below areas. Notification redesigned Picture-in-Picture(PIP)  Visual adaption for different devices  Battery life improved Setting app reorganized Notification redesigned: Android O notification changes includes more easy and manageable way to manager your notification behavior and settings. It includes: Notification Channel: Notification channel allows you to create user customizable channel for each type of notification you wanna display. A single application can have multiple channel, a separate channel for each type of notification you wanna display. Having said this, you can create s separate channel for audio & image notification. User can disable specific notification channe...

Overview of how to develop native code with Android NDK:

  Create a jni directory and place native source code under $PROJECT/jni/... Create Android.mk directory and place it under $PROJECT/jni/... to describe source code to the NDK build system. Create Application.mk and place it under $PROJECT/jni/...to describe project in more details to the NDK build system.It is an optional. Finally need to build native source code by running '$NDK/ndk-build' from project directory or it's sub-directory. Android.mk An Android.mk file is a small build script that we write to describe sources to the NDK build system. It's syntax is like this... LOCAL_PATH:=$(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE:=hello-jni LOCAL_SRC_FILES:=hello-jni.c include $(BUILD_SHARED_LIBRARY) NDK groups your sources into "modules", where each module can be one of the following: Static library Shared library We can write several module in a single 'Android.mk' or can write seve...