Question Detail

What is android Volley?

11 days ago Views 47 Visit Post Reply

I want to use web services which has some headers and body parameters, for now, I am using Asynk Task which is working quite easy and trusted lib. so why we need to Volley, what is actually Volley lib How to use it?
Image result for android volley


Thread Reply

Hemant Sharma

- 11 days ago

These days almost all the mobile application need to send network request to perform their task which will be shared with others. so every developer needs to be the fast request and get a quick response for the task because network tasks are generally a very time-consuming process. Android sending requests using HttpsURLConnection that too on a background thread and then sending the response back on the main thread might make you believe that performing network operations is very complicated in Android. Fortunately, Android Volley has made it pretty simple.

Below we have elaborate step by step implementation of volley lib

 

Step 1. You have to add a volley dependence in your app level gradle which will allow you to get all volley features in your Application Latest Volley Version

dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.1'
}

Step 2. Create MainApplication file which will extends Application for to support to handle all request in a sequence 

import android.app.Application;

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

public class MainApplication extends Application {

    private RequestQueue requestQueue;
    private static MainApplication mInstance;
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }
    public static synchronized MainApplication getInstance() {
        return mInstance;
    }
    /*
    Create a getRequestQueue() method to return the instance of
    RequestQueue.This kind of implementation ensures that
    the variable is instatiated only once and the same
    instance is used throughout the application
    */
    public RequestQueue getRequestQueue() {
        if (requestQueue == null)
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        return requestQueue;
    }
    /*
    public method to add the Request to the the single
    instance of RequestQueue created above.Setting a tag to every
    request helps in grouping them. Tags act as identifier
    for requests and can be used while cancelling them
    */
    public void addToRequestQueue(Request request, String tag) {
        request.setTag(tag);
        getRequestQueue().add(request);
    }
    /*
    Cancel all the requests matching with the given tag
    */
    public void cancelAllRequests(String tag) {
        getRequestQueue().cancelAll(tag);
    }
}

Step 3. Add your MainApplication in your manifest.xml file

<uses-permission android:name="android.permission.INTERNET"/>
<application
    ...
    android:name=".VolleyAPIPack.MainApplication">
...
</application>

Step 4. Now you need to create APIClass which will handle your API request to set GET, POST methods with Params for header and Body

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainAPIClass {
    public static int GETMETHOD = 0;
    public static int POSTMETHOD = 1;
    APIResponce apiResponce;

    public MainAPIClass(String URL, ArrayList<ParamsData>  paramsDataArrayList,APIResponce _apiResponce) {
        int method = GETMETHOD;
        if (paramsDataArrayList != null && paramsDataArrayList.size()>0) {
            method = POSTMETHOD;
            JSONObject postparams = new JSONObject();
            try {
                for (ParamsData param : paramsDataArrayList) {
                    postparams.put(param.getKEY(), param.getVALUE());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            requestMethod(URL, method, postparams);
        } else {
            requestMethod(URL, method, null);
        }
        this.apiResponce=_apiResponce;
    }

    private void requestMethod(String url, int method, JSONObject postparams) {
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(method, url, postparams,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("RequestResponce", "" + response);
                        apiResponce.onAPIResponse(response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("RequestResponce_ERROR", "" + error);
                        apiResponce.onAPIError(error.toString());
                    }
                })
        {
            /** Passing some request headers* */
            @Override
            public Map getHeaders() throws AuthFailureError {
                HashMap headers = new HashMap();
                //headers.put("Content-Type", "application/json");
                headers.put("APIKEY", "4IF_YOU_HAVE_ANY_HEADERbb");
                return headers;
            }
        }
        ;
        // Adding the request to the queue along with a unique string tag
        MainApplication.getInstance().addToRequestQueue(jsonObjReq, "VBage_Volley");
    }

}

Step 5. To set and get body parameters we have to create ParamsData class.

public class ParamsData {
    String KEY,VALUE;

    public ParamsData(String key,String value){
        this.KEY=key;
        this.VALUE=value;
    }
    public String getKEY() {
        return KEY;
    }

    public String getVALUE() {
        return VALUE;
    }
}

Step 6. To get the response on our Activity from API class we need to create an abstract class

public abstract class APIResponce {
    public abstract void onAPIResponse(String str);
    public abstract void onAPIError(String str);

}

Step 7. Now you need to call your API from your Activity or any class by using below function

             Step 7.1: Request to GET method

String url = "https://jsonplaceholder.typicode.com/todos/1"; //HERE-YOUR-COMPLETE-API-URL
new MainAPIClass(url,null);

 
            Step 7.2: Request to the POST method

String url = "https://HERE-YOUR-COMPLETE-POST-API-URL";
ArrayList<ParamsData> paramsData=new ArrayList<>();
paramsData.add(new ParamsData("POSTID","2"));// add your body Params
paramsData.add(new ParamsData("POSTSEC","Details"));
new MainAPIClass(url, paramsData, new APIResponce() {
    @Override
    public void onAPIResponse(String str) {
        response_TextView.setText(str);
    }

    @Override
    public void onAPIError(String str) {
        response_TextView.setText(str);
    }
});


Complete Code GitHub