Volley In Android

By
Volley Android

Why volley in Android ?

Most of the developer used Apache library for the network request. but Apache library not given more updates for supporting android. That’s while android needs one powerful fully support library.Overcome this problem android officially include Volley In Android.

What is volley

Volley is HTTP library that makes the rest-api request for Android app easier and most importantly faster way.

Advantage of volley

  • Simple to integration

    Volley library integration is very simple. first we need to know about network request and which kind of request and response we need. if we need json or string request that time mention on this. like string or json request.

  • Fast to retrieve response

Volley is very fast to respond to all network request. we no need to describe or write lengthy code for it.

  • Care of Asyn task

    Asyn task most of the way use for background request. while in Volley in android asyn task not available. Volley automatically takes the care of this.

  • Customizable

    Volley library is customizable, it’s easy to send string and json request. and get appropriate way to response.

Here we provide simple structure and function to get response and request using volley.

Step 1 :

First  we need to import volley library into project. go to application level buil.gradle file and write the following line in this.

implementation 'com.android.volley:volley:1.1.0'

after writing syns the build.gradle.

build.gradle file look like this,

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "volleyapirequest.lifs.co.in"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'com.android.volley:volley:1.1.0'
    implementation 'com.android.support:multidex:1.0.3'
}

In this file we set compileSdkVersion is 28 and volley library write in dependencies braces.

Step 2 :

Create one Myapplication class extends with Application, that contains all method related to network request. like add in queue, get instance etc.

public class MyApplication extends Application {

}

In this braces we need to write function like add request in queue. get instance of the activity and application etc.

public static final String TAG = MyApplication.class.getSimpleName();

private RequestQueue mRequestQueue;

private static MyApplication mInstance;
private static Context mCtx;
@Override
public void onCreate() {
 super.onCreate();
 mInstance = this;
}

@Override
public void attachBaseContext(Context base) {
 super.attachBaseContext(base);
try {
 MultiDex.install(this);
} catch (RuntimeException multiDexException) {
 multiDexException.printStackTrace();
}
}

public static synchronized MyApplication getInstance(Context context) {
 return mInstance;
}

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

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

Step 3 :

Now we create interface for the response and error. this interface notify our response and error in required class.

create ResponseResultListener interface, this interface look like this,

package volleyapirequest.lifs.co.in.interfaces;

import com.android.volley.VolleyError;

public interface ResponseResultListener {
    public void onSuccess(String requestName, String response);

    public void onError(String requestName, VolleyError error);
}

above interface have two methods, one for onSuccess and another is onError.
onSuccess is used to send success response and onError is used to notify the error response on required class.

Step 4 :

after the interface create GET and POST function.
this function request the server for the specific method.

package volleyapirequest.lifs.co.in.services;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

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

import volleyapirequest.lifs.co.in.MyApplication;
import volleyapirequest.lifs.co.in.interfaces.ResponseResultListener;

public class RequestUtils {
Context mContext;
/*POST API CALL*/

public void API_POST_Login_Call(final String email, final String password, final ResponseResultListener responseResultListener) {
final String url = "http://xyz.com/login"/*Write here login api url*/;

try {
StringRequest postFetchRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseResultListener.onSuccess("api name", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
setErrorResponse("", responseResultListener, error);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();

params.put("email", email);
params.put("password", password);

return params;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
return headers;
}
};
setRetryPolicy(postFetchRequest, "Write your API NAME");
MyApplication.getInstance(mContext).addToRequestQueue(postFetchRequest);
} catch (Exception e) {
}
}

/*GET API CALL*/
public void API_GET_Call(final ResponseResultListener responseResultListener) {
String url = "write your api";
String headerUrl = "";
try {
final String finalHeaderUrl = headerUrl;

final String finalUrl = url;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseResultListener.onSuccess("Write Yout api name", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
setErrorResponse("Write Yout api name", responseResultListener, error);
}
}) {
/*SetHeder*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
return headers;
}
};
setRetryPolicy(stringRequest, "Write Yout api name");
MyApplication.getInstance(mContext).addToRequestQueue(stringRequest);
} catch (Exception e) {
}
}

private void setRetryPolicy(StringRequest stringRequest, String API_TAG) {
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(200000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}

private void setErrorResponse(String apiname, ResponseResultListener responseResultListener, VolleyError error) {
if (error == null || error.networkResponse == null) {
responseResultListener.onError("API NAME", error);
return;
}
}

}

Here API_POST_Login_Call function is using POSt method for send request with parameter.
While we use two parameter email and password as a request parameter in this method.

protected Map<String, String> getParams() {
    Map<String, String> params = new HashMap<String, String>();

    params.put("email", email);
    params.put("password", password);

    return params;
}

above function is post request, required parameter pass here.
if we have any request parameter that all are pass here.

</pre><pre>public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    return headers;
}</pre><pre>

so, getHeader() function is used to pass header in this function. Whenever we need to provide more security in network request that time most of the use headers.
If we required to pass any multiple or single header pass in this functions.

private void setRetryPolicy(StringRequest stringRequest, String API_TAG) {
        stringRequest.setShouldCache(false);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(200000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}

while setRetryPolicy dunction is used to call again our network request. In this function we use ‘200000’ millisecond, used to timeout the our network request and this function require two more parameter like DefaultRetryPolicy.DEFAULT_MAX_RETRIES and DefaultRetryPolicy.DEFAULT_BACKOFF_MULT.

Step 5 :

Now we required to call this method , so we create one activity called as MainActivity and call this mehtod in this Activity.


mRequestUtils.API_POST_Login_Call("xyz@xyz.com", "xyz", new ResponseResultListener() {
@Override
public void onSuccess(String requestName, String response) {
/*Succss process*/
}

@Override
public void onError(String requestName, VolleyError error) {
/*Error process*/
}
});

This code get response from the server and display here.

MainActivity look like this,


package volleyapirequest.lifs.co.in;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.android.volley.VolleyError;

import volleyapirequest.lifs.co.in.interfaces.ResponseResultListener;
import volleyapirequest.lifs.co.in.services.RequestUtils;

public class MainActivity extends AppCompatActivity {

private RequestUtils mRequestUtils;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mRequestUtils.API_POST_Login_Call("xyz@xyz.com", "xyz", new ResponseResultListener() {
@Override
public void onSuccess(String requestName, String response) {
/*Succss process*/
}

@Override
public void onError(String requestName, VolleyError error) {
/*Error process*/
}
});


mRequestUtils.API_GET_Call(new ResponseResultListener() {
@Override
public void onSuccess(String requestName, String response) {
/*Succss process*/
}

@Override
public void onError(String requestName, VolleyError error) {
/*Error process*/
}
});
}
}

Latest Blog