TrinityTuts

Working with android volley library

Last updated on November 24th, 2018 at 09:08 pm

Android Volley is Asynchronous HTTP Requests library which helps to make network calls very efficiently and easily. Volley is faster and it takes less than a minute to setup volley into your project. You don’t need to write long code to make the call and write Async task to make network calls, Volley handle all this by its own and the best part it create other thread and you can add no of calls to the server by adding request into the queue.

 

Most useful features of Android Volley

  1. Automatic scheduling of network requests.
  2. Effective request cache and memory management
  3. Support for request prioritization.
  4. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.

To read more feature of volley library you can read this official Google Volley post.

Installing and using Android Volley in project

Step 1. Create a project in your Android Studio and add Volley dependencies in your build.gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0.0'
    compile 'com.android.volley:volley:1.0.0'
}

after adding dependence you can synchronize your project to install dependence. 

Step 2. Now we can create a new java class in our project which extends Application this is our main application in which we can initialize Volley and also create a new method in which we can add request queue and cancel request as show in below  code

package com.volleyexample;

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
 * Created by aneh on 8/8/17.
 */

public class AppController extends Application {
    public static final String TAG = AppController.class
            .getSimpleName();
    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

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

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

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

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

Making asynchronous HTTP requests with Volley

Volley provides the following utility classes which you can use to make asynchronous HTTP requests:

Create your first JsonObjectRequest and set header

Before we start, please keep one thing in mind the request is based on the data which you get from web service if you get JsonObject in starting of service as shown below then you can use JsonObjectRequest 

{
  "name": "Aneh Thakur",
  "status": "Love think Code :)"
}

But if your service contains JsonArray then you need to make JsonArrayRequest

[
  {"name": "Aneh Thakur"},
  {"name": "Amit"},
  {"name": "Ajay"},
]

If you’re not sure then you can simply use String Request.

Now edit your MainActivity.java and inside your onCreate we can make our first call

String url ="Link_TO_JSON_OBJECT";

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

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // Handel Errors
                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    Log.e(TAG, error.getMessage());
                } else if (error instanceof AuthFailureError) {
                    Log.e(TAG, error.getMessage());
                } else if (error instanceof ServerError) {
                    Log.e(TAG, error.getMessage());
                } else if (error instanceof NetworkError) {
                    Log.e(TAG, error.getMessage());
                } else if (error instanceof ParseError) {
                    Log.e(TAG, error.getMessage());
                }
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("authorization", "Bearer Your_Token_IF_YOUNEED");
                return headers;
            }
        };
        
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjReq);

In above code first, we create JsonObjectRequest object and we pass some parameter in it as shown below

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request_METHOD, WEB_API_URL, CUSTOM_REQUEST_PARAMETER_ELSE_NULL, HANDEL_RESPONSE_ERROR){ SET_HEADER|SET_PARAMETER }

If you want to pass header with your request you can override getHeaders() method as shown in above code. We can call volley object from our main application and add or request in queue

AppController.getInstance().addToRequestQueue(jsonObjReq);

Create JsonArrayRequest using Volley

JsonArrayRequest is same as JsonObjectRequest only you need to replace JsonObjectRequest With JsonArrayRequest but keep in mind you response data in JsonArray format.

        String url= "Your_Json_Array.json"
        JsonArrayRequest jsonArrReq = new JsonArraytRequest(Request.Method.POST,
                url, null,
                new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // Handel error as i show in JsonObjectRequest
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonArrReq);

Create String Request in Volley

String request is used when you want to load data as a string.

        String url= "Your_Json_Array.json"
        StringRequest stringReq = new StringRequest(Request.Method.POST,
                url, null,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, response.toString());
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // Handel error as i show in JsonObjectRequest
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(stringReq);

Post form data using Volley

If you want to post form data to the server you need to create custom request and pass it to request function as shown below.

        String url = "Your Form Submit Api Link";
        /* Create request */
        Map<String,String> params = new HashMap<String, String>();
        params.put("username", "aneh");
        params.put("password", "123");

        JsonObjectRequest loginForm = new JsonObjectRequest(com.android.volley.Request.Method.POST,
                url, new JSONObject(params),
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    Log.e(TAG, error.getMessage());
                } else if (error instanceof AuthFailureError) {
                    Log.e(TAG, error.getMessage());
                } else if (error instanceof ServerError) {
                    Log.e(TAG, error.getMessage());
                } else if (error instanceof NetworkError) {
                    Log.e(TAG, error.getMessage());
                } else if (error instanceof ParseError) {
                    Log.e(TAG, error.getMessage());
                }
            }
        });
        AppController.getInstance().addToRequestQueue(loginForm);

Cancelling Volley Request

In Volley Android library there is two way to cancel request first we can cancel only selected request and other we can cancel all the requests. If you remember addToRequestQueue() which we create in our main application class have two parameters one for the request and other for TAG, with the help of this tag we can cancel selected request as shown below.

Cancel single request in Volley

String request_tag = "my_req";
AppController.getInstance().getRequestQueue().cancelAll(request_tag);

Cancel all requests in Volley

To cancel of all request in your queue you just need to call cancelAll() it cancel all your request.

AppController.getInstance().getRequestQueue().cancelAll();

Demo: I use volley library in one of my e-commerce application Offloo

If this post helps you to understand working with Android Volley library, then please subscribe, our blog Also do Like our Facebook Page or Add us on Twitter.