90 likes | 116 Views
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub.
E N D
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 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;}
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;
@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<>();
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();}
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();
} @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){ } } } }