Volley – Android Networking Library by Google

Posted on Posted in Android

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub.

Volley offers the following benefits:

  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.

Volley excels at RPC-type operations used to populate a UI, such as fetching a page of search results as structured data. It integrates easily with any protocol and comes out of the box with support for raw strings, images, and JSON. By providing built-in support for the features you need, Volley frees you from writing boilerplate code and allows you to concentrate on the logic that is specific to your app.

Volley is not suitable for large download or streaming operations, since Volley holds all responses in memory during parsing. For large download operations, consider using an alternative like DownloadManager.

The core Volley library is developed on GitHub and contains the main request dispatch pipeline as well as a set of commonly applicable utilities, available in the Volley “toolbox.” The easiest way to add Volley to your project is to add the following dependency to your app’s build.gradle file:

dependencies {
    ...
    compile 'com.android.volley:volley:1.0.0'
}

Permissions Required:

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

Initialize Volley in you MyApplication Class:

private RequestQueue requestQueue;

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

public <T> void addRequestToQueue(Request<T> requestQueue, String tag) {
    requestQueue.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(requestQueue);


}

public <T> void addRequestToQueue(Request<T> requestQueue) {
    requestQueue.setTag(TAG);
    getRequestQueue().add(requestQueue);
}

public void cancelPendingRequests(Object tag) {
    if (requestQueue != null) {
        requestQueue.cancelAll(tag);
    }
}

Volley Functions :

1] Get Request

// Volley String Get Request
public void getGETStringRequest(final Context context, String url, final VolleyCallback callback) {

    Log.i("url", url);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("DriverResponse", response.toString());

            callback.onSuccess(response);


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error", error.toString());

            try{
                String json = null;
                NetworkResponse response = error.networkResponse;
                json = new String(response.data);
                Log.d("Error", json);

                ErrorResponse(json,context);

            }catch (Exception e)
            {
                //Log.d("Error", e.getMessage());
            }
        }
    });

    stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    MyApplication.getInstance().addRequestToQueue(stringRequest, "");
}

2] Get Request with header

// Volley String Get Request with Header
public void getGETStringRequestHeader(final Context context, String url, final Map<String, String> paramsHeaders , final VolleyCallback callback) {


    Log.i("url", url);
    StringRequest postRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    // response
                    Log.d("Response", response);

                    callback.onSuccess(response);
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    //Log.d("ERROR","error => "+error.toString());


                    try{
                        String json = null;
                        NetworkResponse response = error.networkResponse;
                        json = new String(response.data);
                        Log.d("Error", json);

                        ErrorResponse(json,context);

                    }catch (Exception e)
                    {
                        //Log.d("Error", e.getMessage());
                    }
                }
            }
    ) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            /*Map<String, String> params = new HashMap<String, String>();
            params.put("User-Agent", "Nintendo Gameboy");*/

            return paramsHeaders;
        }
    };

    postRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    MyApplication.getInstance().addRequestToQueue(postRequest, "");
}

3] String Request DELETE with header

// Volley String Delete Request with Header
public void getDeleteStringRequestHeader(final Context context, String url, final Map<String, String> paramsHeaders , final VolleyCallback callback) {

     Log.i("url", url);



    StringRequest postRequest = new StringRequest(Request.Method.DELETE, url,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    // response
                    Log.d("Response", response);

                    callback.onSuccess(response);
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    //Log.d("ERROR","error => "+error.toString());


                    try{
                        String json = null;
                        NetworkResponse response = error.networkResponse;
                        json = new String(response.data);
                        Log.d("Error", json);

                        ErrorResponse(json,context);

                    }catch (Exception e)
                    {
                        //Log.d("Error", e.getMessage());
                    }
                }
            }
    ) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            /*Map<String, String> params = new HashMap<String, String>();
            params.put("User-Agent", "Nintendo Gameboy");*/

            return paramsHeaders;
        }
    };

    postRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    MyApplication.getInstance().addRequestToQueue(postRequest, "");
}

4] String Request POST with Header

// Volley String POST Request with Header
public void getPOSTStringRequestHeader(final Context context, String url, final Map<String, String> paramsHeaders , final VolleyCallback callback) {

    Log.i("url", url);
    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    // response
                    Log.d("Response", response);

                    callback.onSuccess(response);
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    //Log.d("ERROR","error => "+error.toString());

                    try{
                        String json = null;
                        NetworkResponse response = error.networkResponse;
                        json = new String(response.data);
                        Log.d("Error", json);

                        ErrorResponse(json,context);

                    }catch (Exception e)
                    {
                        //Log.d("Error", e.getMessage());
                    }
                }
            }
    ) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            /*Map<String, String> params = new HashMap<String, String>();
            params.put("User-Agent", "Nintendo Gameboy");*/

            return paramsHeaders;
        }
    };

    postRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    MyApplication.getInstance().addRequestToQueue(postRequest, "");
}

5] Simple Json Object Request POST

//Volley JSON Object Post Request
public void sendJSONObjectRequest(final Context context, String url, JSONObject jsonObject, final VolleyCallback callback) {

    Log.i("url", url);
    Log.i("JSON CREATED", jsonObject.toString());

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            url, jsonObject,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d("response", response.toString());

                    callback.onSuccess(response.toString());
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //VolleyLog.d("Error", "Error: " + error.getMessage());
           try{
                String json = null;
                NetworkResponse response = error.networkResponse;
                json = new String(response.data);
                Log.d("Error", json);

                ErrorResponse(json,context);

            }catch (Exception e)
            {
                //Log.d("Error", e.getMessage());
            }
        }
    });

    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
            30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    //Adding request to request queue
    MyApplication.getInstance().addRequestToQueue(jsonObjReq, "");

}

6]  Json Object Request with Header

//Volley JSON Object Post Request
public void sendJSONObjectRequestHeader(final Context context, String url, final Map<String, String> paramsHeaders, JSONObject jsonObject, final VolleyCallback callback) {

    Log.i("url", url);
    Log.i("JSON CREATED", jsonObject.toString());

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            url, jsonObject,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d("response", response.toString());

                    callback.onSuccess(response.toString());
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //VolleyLog.d("Error", "Error: " + error.getMessage());
           try{
                String json = null;
                NetworkResponse response = error.networkResponse;
                json = new String(response.data);
                Log.d("Error", json);

                ErrorResponse(json,context);

            }catch (Exception e)
            {
                //Log.d("Error", e.getMessage());
                FireToast.customSnackbar(context, "Oops Something Went Wrong!!", "");
            }
        }
    })

    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            /*Map<String, String> params = new HashMap<String, String>();
            params.put("User-Agent", "Nintendo Gameboy");*/

            return paramsHeaders;
        }
    };;

    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
            30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    //Adding request to request queue
    MyApplication.getInstance().addRequestToQueue(jsonObjReq, "");

}

7] JSON Object PUT Request

//Volley JSON Object Put Request
public void sendJSONObjectPutRequestHeader(final Context context, String url, final Map<String, String> paramsHeaders, JSONObject jsonObject, final VolleyCallback callback) {

    Log.i("url", url);
    Log.i("JSON CREATED", jsonObject.toString());

      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.PUT,
            url, jsonObject,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d("response", response.toString());

                    callback.onSuccess(response.toString());
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //VolleyLog.d("Error", "Error: " + error.getMessage());

            try{
                String json = null;
                NetworkResponse response = error.networkResponse;
                json = new String(response.data);
                Log.d("Error", json);

                ErrorResponse(json,context);

            }catch (Exception e)
            {
                //Log.d("Error", e.getMessage());
                FireToast.customSnackbar(context, "Oops Something Went Wrong!!", "");
            }
        }
    })

    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            /*Map<String, String> params = new HashMap<String, String>();
            params.put("User-Agent", "Nintendo Gameboy");*/

            return paramsHeaders;
        }
    };;

    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
            30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    //Adding request to request queue
    MyApplication.getInstance().addRequestToQueue(jsonObjReq, "");

}

8] Call back interface and Error Handling

public interface VolleyCallback{
    void onSuccess(String result);
}
private void ErrorResponse(String Response,Context context)
{
    gson = new Gson();
    errorPOJO = gson.fromJson(Response, ErrorPOJO.class);

    if(errorPOJO.getErrors() != null)
    {
        String[] error = errorPOJO.getErrors();
        String errorString = error[0];

        FireToast.customSnackbar(context, errorString,"");

    }
    else if(errorPOJO.getMessage() != null)
    {
        FireToast.customSnackbar(context, errorPOJO.getMessage(),"");
    }
    else
    {
        FireToast.customSnackbar(context, "Oops Something Went Wrong!!","");
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *