1 / 9

Implementing a Custom Request Using Volley Library

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub.

Télécharger la présentation

Implementing a Custom Request Using Volley Library

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Implementing a Custom Request Using Volley Library

  2. 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

  3. Create the Model Response class : public class ServiceResponse {String data; public String getData() {return data;} public void setData(String data) {this.data = data;}public intgetType() {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 intreequesttype;String  postdata;intpostdatv=1;}

  4. protected Response.ListenermListener;public VolleyCustomRequest(String url, Response.ErrorListener listener) {super(url, listener);}public VolleyCustomRequest(int method, String url, Response.Listener listener1, @NullableResponse.ErrorListener listener, String postdata, intreequesttype) {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, @NullableResponse.ErrorListener listener, intreequesttype) {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, intrequestType) {super(Method.POST, url,listener);this.reequesttype=requestType;this.mListener=listener1;this.params=params;

  5. @Overrideprotected 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;} @Overrideprotected VolleyErrorparseNetworkError(VolleyErrorvolleyError) { ServiceResponse s=new ServiceResponse();s.setData(volleyError.getLocalizedMessage());s.setType(reequesttype);return super.parseNetworkError(volleyError);} @Overrideprotected void deliverResponse(Object response) {mListener.onResponse(response); } @Overridepublic Map<String, String> getHeaders() throws AuthFailureError {Map<String,String> params = new HashMap<>();

  6. params.put(“Content-Type”,”application/x-www-form-urlencoded”);return params;}@Overrideprotected 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 {EditTextet_email;TextViewback,submit;LoadingDialogloadingDialog; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.forgotpassword_layout);init();}

  7. 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);} @Overridepublic 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();

  8. } @Overridepublic void onResponse(Object response) {loadingDialog.stop();ServiceResponceserviceResponce=(ServiceResponce)response; if(serviceResponce.getType()==3) { try { // here you get service responseJSONObjectjsonObject = 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){ } } } }

More Related