Volley Library in Android
Volley is an HTTP library that makes networking very easy and fast, for Android apps. It was developed by Google and introduced during Google I/O 2013. It was developed because there is an absence in Android SDK, of a networking class capable of working without interfering with the user experience. Although Volley is a part of the Android Open Source Project(AOSP), Google announced in January 2017 that Volley will move to a standalone library. It manages the processing and caching of network requests and it saves developers valuable time from writing the same network call/cache code again and again.
Volley is not suitable for large download or streaming operations since Volley holds all responses in memory during parsing.
Features of Volley:
- Request queuing and prioritization
- Effective request cache and memory management
- Extensibility and customization of the library to our needs
- Cancelling the requests
Advantages of using Volley:
- All the task that need to be done with Networking in Android, can be done with the help of Volley.
- Automatic scheduling of network requests.
- Catching
- Multiple concurrent network connections.
- Cancelling request API.
- Request prioritization.
- Volley provides debugging and tracing tools.
How to Import Volley and add Permissions:
Before getting started with Volley, one needs to import Volley and add permissions in the Android Project. The steps to do so are as follows:
- Create new project.
- Open build.gradle(Moule: app) and add the following dependency:
dependencies{ //... implementation 'com.android.volley:volley:1.0.0' } - In AndroidMaifest.xml add the internet permission:
<uses-permission android:name="android.permission.INTERNET />"
Classes in Volley Library:
Volley has two main classes:
- Request Queue: It is the interest one uses for dispatching requests to the network. One can make a request queue on demand if required, but typically it is created early on, at startup time, and keep it around and use it as a Singleton.
- Request: All the necessary information for making web API call is stored in it. It is the base for creating network requests(GET, POST).
Types of Request using Volley Library:
- String Request
StringRequeststringRequest=newStringRequest(Request.Method.GET,url,newResponse.Listener() {@OverridepublicvoidonResponse(String response){}},newResponse.ErrorListener() {@OverridepublicvoidonErrorResponse(VolleyError error){}});requestQueue.add(stringRequest);</pre>chevron_rightfilter_none - JSONObject Request
JsonObjectRequestjsonObjectRequest=newJsonObjectRequest(Request.Method.GET,url,null,newResponse.Listener() {@OverridepublicvoidonResponse(JSONObject response){}},newResponse.ErrorListener() {@OverridepublicvoidonErrorResponse(VolleyError error){}});requestQueue.add(jsonObjectRequest);chevron_rightfilter_none - JSONArray Request
JsonArrayRequestjsonArrayRequest=newJsonArrayRequest(Request.Method.GET,url,null,newResponse.Listener() {@OverridepublicvoidonResponse(JSONArray response){}},newResponse.ErrorListener() {@OverridepublicvoidonErrorResponse(VolleyError error){}});requestQueue.add(jsonArrayRequest);chevron_rightfilter_none - Image Request
intmax - width = ...;intmax_height = ...;ImageRequestimageRequest=newImageRequest(URL,newResponse.Listener() {@OverridepublicvoidonResponse(Bitmap response){// Assign the response// to an ImageViewImageViewimageView= (ImageView)findViewById(R.id.imageView);imageView.setImageBitmap(response);}},max_width, max_height,null);requestQueue.add(imageRequest);chevron_rightfilter_none - Adding Post Parameters
String tag_json_obj ="json_obj_req";StringurlProgressDialog pDialog =newProgressDialog(this);pDialog.setMessage("Loading...PLease wait");pDialog.show();JsonObjectRequestjsonObjReq=newJsonObjectRequest(Method.POST,url,null,newResponse.Listener() {@OverridepublicvoidonResponse(JSONObject response){Log.d(TAG, response.toString());pDialog.hide();}},newResponse.ErrorListener() {@OverridepublicvoidonErrorResponse(VolleyError error){VolleyLog.d(TAG,"Error: "+ error.getMessage());pDialog.hide();}}) {@OverrideprotectedMap getParams(){Map params =newHashMap();params.put("name","Androidhive");params.put("email","abc@androidhive.info");params.put("password","password123");returnparams;}};AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);chevron_rightfilter_none - Adding Request Headers
String tag_json_obj ="json_obj_req";StringurlProgressDialog pDialog =newProgressDialog(this);pDialog.setMessage("Loading...");pDialog.show();JsonObjectRequestjsonObjReq=newJsonObjectRequest(Method.POST,url,null,newResponse.Listener() {@OverridepublicvoidonResponse(JSONObject response){Log.d(TAG, response.toString());pDialog.hide();}},newResponse.ErrorListener() {@OverridepublicvoidonErrorResponse(VolleyError error){VolleyLog.d(TAG,"Error: "+ error.getMessage());pDialog.hide();}}) {@OverridepublicMap getHeaders()throwsAuthFailureError{HashMap headers =newHashMap();headers.put("Content-Type","application/json");headers.put("apiKey","xxxxxxxxxxxxxxx");returnheaders;}};AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);chevron_rightfilter_none - Handling the Volley Cache
// Loading request from cacheCachecache= AppController.getInstance().getRequestQueue().getCache();Entry entry = cache.get(url);if(entry !=null) {try{Stringdata=newString(entry.data,"UTF-8");// handle data, like converting it// to xml, json, bitmap etc.,}catch(UnsupportedEncodingException e) {e.printStackTrace();}}}else{// If cached response doesn't exists}// Invalidate cacheAppController.getInstance().getRequestQueue().getCache().invalidate(url,true);// Turning off cache// String requestStringRequeststringReq=newStringRequest(....);// disable cachestringReq.setShouldCache(false);// Deleting cache for particular cache</strong>AppController.getInstance().getRequestQueue().getCache().remove(url);// Deleting all the cacheAppController.getInstance().getRequestQueue().getCache().clear(url);chevron_rightfilter_none - Cancelling Request
// Cancel single requestString tag_json_arry ="json_req";ApplicationController.getInstance().getRequestQueue().cancelAll("feed_request");// Cancel all requestApplicationController.getInstance().getRequestQueue().cancelAll();chevron_rightfilter_none - Request Prioritization
privatePriority priority = Priority.HIGH;StringRequeststrReq=newStringRequest(Method.GET,Const.URL_STRING_REQ,newResponse.Listener() {@OverridepublicvoidonResponse(String response) {Log.d(TAG, response.toString());msgResponse.setText(response.toString());hideProgressDialog();} },newResponse.ErrorListener() {@OverridepublicvoidonErrorResponse(VolleyError error) {VolleyLog.d(TAG,"Error: "+ error.getMessage());hideProgressDialog();} }) {@OverridepublicPriority getPriority(){returnpriority;}};chevron_rightfilter_none
Recommended Posts:
- Image loading and caching library for Android | Set 1
- Image loading and caching library for Android | Set 2
- Android | AdMob Banner Ads for Android Studio
- Android | AdMob Interstitial Ads for Android Studio
- Android | Android Application File Structure
- Android | How to add Radio Buttons in an Android Application?
- Android | How to Request permissions in Android Application?
- Android | Starting with first app/android project
- Android | Running your first Android app
- Android | 8.0 Oreo
- How to use WebView in Android
- How to use CheckBox in Android
- Android | App to Add Two Numbers
- Android | RecyclerView
- Android System Architecture
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : smodi2007



