Why we use Volley Library?

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 back off.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools

Things You Need to Do:

  • Extend the Request<T>class, where <T> represents the type of parsed response the request expects. So if your parsed response is a string, for example, create your custom request by extending Request<String>.
  • Add Gson library compile dependency to your app-level build.gradle
  • Create a model class as per response.
  • Add custom request to request queue of volley

Create the Model Response class :

public class ServiceResponse {
String data;

public String getData() {
return data;
}

public void setData(String data) {
this.data = data;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
int type;
}

Create CustomRequest  class :

public class VolleyCustomRequest extends Request<Object>{
Map<String, String> params;
protected int reequesttype;
String  postdata;
int postdatv=1;

protected Response.Listener mListener;
public VolleyCustomRequest(String url, Response.ErrorListener listener) {
super(url, listener);
}
public VolleyCustomRequest(int method, String url, Response.Listener listener1, @Nullable Response.ErrorListener listener, String postdata, int reequesttype) {
super(Method.POST, url, listener);
this.reequesttype=reequesttype;
this.mListener=listener1;
this.postdata=postdata;
this.postdatv=2;

}
public VolleyCustomRequest(int method, String url, Response.Listener listener1, @Nullable Response.ErrorListener listener, int reequesttype) {
super(Method.GET, url, listener);
this.reequesttype=reequesttype;
this.mListener=listener1;
}
public VolleyCustomRequest(int m, String url, Response.Listener listener1, Response.ErrorListener listener, Map<String, String> params, int requestType) {
super(Method.POST, url,listener);
this.reequesttype=requestType;
this.mListener=listener1;
this.params=params;
}

@Override
protected Response<Object> parseNetworkResponse(NetworkResponse response) {
String jsonData=new String(response.data);
ServiceResponce s=new ServiceResponce();
s.setData(jsonData);
s.setType(reequesttype);
Response<Object> resp = Response.success((Object) (s), HttpHeaderParser.parseCacheHeaders(response));
return resp;
}

@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {

ServiceResponse s=new ServiceResponse();
s.setData(volleyError.getLocalizedMessage());
s.setType(reequesttype);
return super.parseNetworkError(volleyError);
}

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

}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put(“Content-Type”,”application/x-www-form-urlencoded”);
return params;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
 @Override

public byte[] getBody() throws AuthFailureError {
return postdata.getBytes();
}

}

Let’s use volley custom request in your app :

public class YourActivity  extends AppCompatActivity implements Response.Listener,Response.ErrorListener {
EditText et_email;
TextView back,submit;
LoadingDialog loadingDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.forgotpassword_layout);
init();
}
public  void init()
{
HashMap<String, String> amp = new HashMap<>();
amp.put(“user_id”,et_email.getText().toString());
loadingDialog = new LoadingDialog(ForgotPasswordActivity.this);
loadingDialog.showDialog();
VolleyCustomRequest request = new VolleyCustomRequest(Request.Method.POST, “your url”, this, this, amp, 3);
RequestQueue queue = Volley.newRequestQueue(ForgotPasswordActivity.this);
queue.add(request);
}

@Override
public void onErrorResponse(VolleyError error) {
loadingDialog.stop();
Snackbar.with(this,null)
.type(Type.ERROR)
.message(“Some Problem Occure”)
.duration(Duration.SHORT)
.fillParent(true)
.textAlign(Align.LEFT)
.show();

}

@Override
public void onResponse(Object response) {
loadingDialog.stop();
ServiceResponce serviceResponce=(ServiceResponce)response;

if(serviceResponce.getType()==3)

{

try {

// here you get service response
JSONObject jsonObject = new JSONObject(serviceResponce.getData());
String message=jsonObject.getString(“message”);
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
Snackbar.with(this,null)
.type(Type.SUCCESS)
.message(message)
.duration(Duration.SHORT)
.fillParent(true)
.textAlign(Align.LEFT)
.show();
}
catch (Exception e)
{

}

}

}

}