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.
We have seen Volley library automatically call API once more when we call an API. In our case when we request a multipart API then We look that Volley request once more with same data of the first request, So how we detect auto request?
We can solve it by the setRetryPolicy method of Request class.
1 2 3 4 5 6 |
multipartRequest.setRetryPolicy(new DefaultRetryPolicy( 30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); multipartRequest.setShouldCache(false); MySingleton.getInstance(this).addToRequestQueue(multipartRequest); |
above multipartRequest is the object instance of Request class.
Now Full request code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
String url = AppCredential.URL.replace("api/", "") + "?dispatch=wk_mobikul_upload_image.wk_img"; Log.d("url", url + ""); MultipartRequest multipartRequest = new MultipartRequest(Request.Method.POST, url, null, mimeType, multipartBody, new Response.Listener<NetworkResponse>() { @Override public void onResponse(NetworkResponse response) { isFileUploaded = true; Log.d("Ashwini", new String(response.data)); preperData(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { try { if (progressDialog != null) progressDialog.dismiss(); Toast.makeText(getApplicationContext(), R.string.try_again, Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } }); multipartRequest.setRetryPolicy(new DefaultRetryPolicy( 30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); multipartRequest.setShouldCache(false); MySingleton.getInstance(this).addToRequestQueue(multipartRequest); |
References: https://developer.android.com/training/volley/index.html