Volley Library In Android - GeeksforGeeks

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:

  1. Request queuing and prioritization
  2. Effective request cache and memory management
  3. Extensibility and customization of the library to our needs
  4. Cancelling the requests

Advantages of Using Volley

  1. All the tasks that need to be done with Networking in Android, can be done with the help of Volley.
  2. Automatic scheduling of network requests.
  3. Catching
  4. Multiple concurrent network connections.
  5. Cancelling request API.
  6. Request prioritization.
  7. Volley provides debugging and tracing tools.

To take your network operations to the next level using Kotlin, the Android Mastery with Kotlin: Beginner to Advanced course covers how to implement libraries like Volley in Kotlin-based apps

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 a new project. Open build.gradle(Module: app) and add the following dependency:

dependencies{ //... implementation 'com.android.volley:volley:1.2.1'}

In AndroidManifest.xml add the internet permission:

<uses-permission android:name="android.permission.INTERNET" />

Classes in Volley Library

Volley has two main classes:

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

There are many types of request using Volley Library mentioned below:

1. String Request

Java Stringurl="https:// string_url/"; StringRequeststringRequest =newStringRequest( Request.Method.GET,url, newResponse.Listener(){ @Override publicvoidonResponse(Stringresponse) { } }, newResponse.ErrorListener(){ @Override publicvoidonErrorResponse(VolleyErrorerror) { } }); requestQueue.add(stringRequest);

2. JSONObject Request

Java Stringurl="https:// json_url/"; JsonObjectRequest jsonObjectRequest =newJsonObjectRequest( Request.Method.GET,url,null, newResponse.Listener(){ @Override publicvoidonResponse(JSONObjectresponse) { } }, newResponse.ErrorListener(){ @Override publicvoidonErrorResponse(VolleyErrorerror) { } }); requestQueue.add(jsonObjectRequest);

3. JSONArray Request

Java JsonArrayRequest jsonArrayRequest =newJsonArrayRequest( Request.Method.GET, url, null, newResponse.Listener(){ @Override publicvoidonResponse(JSONArrayresponse) { } }, newResponse.ErrorListener(){ @Override publicvoidonErrorResponse(VolleyErrorerror) { } }); requestQueue.add(jsonArrayRequest);

4. Image Request

Java intmax-width=...; intmax_height=...; StringURL="http:// image_url.png"; ImageRequest imageRequest =newImageRequest(URL, newResponse.Listener(){ @Override publicvoid onResponse(Bitmapresponse) { // Assign the response // to an ImageView ImageView imageView =(ImageView) findViewById( R.id.imageView); imageView.setImageBitmap(response); } }, max_width,max_height,null); requestQueue.add(imageRequest);

5. Adding Post Parameters

Java Stringtag_json_obj="json_obj_req"; Stringurl="https:// api.xyz.info/volley/person_object.json"; ProgressDialogpDialog=newProgressDialog(this); pDialog.setMessage("Loading...PLease wait"); pDialog.show(); JsonObjectRequest jsonObjReq =newJsonObjectRequest( Method.POST, url, null, newResponse.Listener(){ @Override publicvoidonResponse(JSONObjectresponse) { Log.d(TAG,response.toString()); pDialog.hide(); } }, newResponse.ErrorListener(){ @Override publicvoidonErrorResponse(VolleyErrorerror) { VolleyLog.d(TAG,"Error: " +error.getMessage()); pDialog.hide(); } }){ @Override protectedMapgetParams() { Mapparams=newHashMap(); params.put("name","Androidhive"); params.put("email","abc@androidhive.info"); params.put("password","password123"); returnparams; } }; AppController.getInstance() .addToRequestQueue(jsonObjReq,tag_json_obj);

6. Adding Request Headers

Java Stringtag_json_obj="json_obj_req"; String url ="https:// api.androidhive.info/volley/person_object.json"; ProgressDialogpDialog=newProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsonObjReq =newJsonObjectRequest( Method.POST, url, null, newResponse.Listener(){ @Override publicvoidonResponse(JSONObjectresponse) { Log.d(TAG,response.toString()); pDialog.hide(); } }, newResponse.ErrorListener(){ @Override publicvoidonErrorResponse(VolleyErrorerror) { VolleyLog.d(TAG,"Error: " +error.getMessage()); pDialog.hide(); } }){ @Override publicMapgetHeaders()throwsAuthFailureError { HashMapheaders=newHashMap(); headers.put("Content-Type","application/json"); headers.put("apiKey","xxxxxxxxxxxxxxx"); returnheaders; } }; AppController.getInstance() .addToRequestQueue(jsonObjReq,tag_json_obj);

7. Handling the Volley Cache

Java // Loading request from cache Cache cache =AppController.getInstance() .getRequestQueue() .getCache(); Entryentry=cache.get(url); if(entry!=null){ try{ String data =newString(entry.data,"UTF-8"); // handle data, like converting it // to xml, json, bitmap etc., } catch(UnsupportedEncodingExceptione){ e.printStackTrace(); } } } else { // If cached response doesn't exists } // Invalidate cache AppController.getInstance() .getRequestQueue() .getCache() .invalidate(url,true); // Turning off cache // String request StringRequest stringReq =newStringRequest(....); // disable cache stringReq.setShouldCache(false); // Deleting cache for particular cache</strong> AppController.getInstance() .getRequestQueue() .getCache() .remove(url); // Deleting all the cache AppController.getInstance() .getRequestQueue() .getCache() .clear(url);

8. Cancelling Request

Java // Cancel single request Stringtag_json_arry="json_req"; ApplicationController.getInstance() .getRequestQueue() .cancelAll("feed_request"); // Cancel all request ApplicationController.getInstance() .getRequestQueue() .cancelAll();

9. Request Prioritization

Java privatePrioritypriority=Priority.HIGH; StringRequest strReq =newStringRequest( Method.GET, Const.URL_STRING_REQ, newResponse .Listener(){ @Override publicvoidonResponse(Stringresponse){ Log.d(TAG,response.toString()); msgResponse.setText(response.toString()); hideProgressDialog(); }}, newResponse .ErrorListener(){ @Override publicvoid onErrorResponse(VolleyErrorerror){ VolleyLog.d(TAG, "Error: " +error.getMessage()); hideProgressDialog(); }}){ @Override publicPrioritygetPriority() { returnpriority; } }; Comment More info Next Article JSON Parsing in Android

V

vartika02 Follow Improve

Từ khóa » Thư Viện Volley Trong Android