123ArticleOnline Logo
Welcome to 123ArticleOnline.com!
ALL >> Technology,-Gadget-and-Science >> View Article

Implementing A Custom Request Using Volley Library

Profile Picture
By Author: Netleaf software
Total Articles: 43
Comment this article
Facebook ShareTwitter ShareGoogle+ ShareTwitter Share

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 Requestclass, where 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.
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{
Map 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 params, int requestType) {
super(Method.POST, url,listener);
this.reequesttype=requestType;
this.mListener=listener1;
this.params=params;
}

@Override
protected Response parseNetworkResponse(NetworkResponse response) {
String jsonData=new String(response.data);
ServiceResponce s=new ServiceResponce();
s.setData(jsonData);
s.setType(reequesttype);
Response 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 getHeaders() throws AuthFailureError {
Map params = new HashMap();
params.put(“Content-Type”,”application/x-www-form-urlencoded”);
return params;
}
@Override
protected Map 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 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)
{

}

}

}

}

Total Views: 27Word Count: 371See All articles From Author

Add Comment

Technology, Gadget and Science Articles

1. Is virtual Flight Simulator helpful For Aviation Training?
Author: Eesha Zaveri

2. Thinking Of An E-commerce Store? Think Magento!
Author: Lisa Brown

3. How To Decide What Type Of Thermal Printer Your Business Needs
Author: Tushar Ghyoal

4. By 2021 Cloud Billing Market Estimated To Grow $16.59 Billion At A Cagr Of 23.9%
Author: siddharth mnm

5. 10 Ways To Become Efficient At Sales Using The Pos Machine
Author: Tushar Ghoyal

6. Professional Machine Vision Inspection System Manufacturer Introduces Machines
Author: focru012356

7. Amplifon Hearing Aids In Langley
Author: Md Nahidul Hasan

8. Accelerate Your Fantasy Football Business With Mobile Applications
Author: Robbie Royce

9. Do Multiple Things With The Pos Billing System!
Author: Sukriti Sinha

10. How To Watch Hulu On Nintendo Switch
Author: Aida Martin

11. Difference Between Huawei 5g Mobile Wifi Pro E6878-370 And E6878-870?
Author: Ericsson ALEX

12. How To Keep Your Iphone Safe
Author: Charlie Wollstonecraft

13. How Do The Experts Help In Resolving Issues With Your Computer?
Author: kirlin jackeline

14. Do You Know Why Website And Mobile App Development Company Is Important?
Author: Ranpariya Consultancy

15. Want To Satisfy Your Cravings? Go For Any Food Delivery Applications
Author: Robbie Royce

Login To Account
Login Email:
Password:
Sign Up Newsletter
Email Address: