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:

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

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:

  1. Create new project.
  2. Open build.gradle(Moule: app) and add the following dependency:
    dependencies{ 
        //...
        implementation 'com.android.volley:volley:1.0.0'
    }
    
  3. In AndroidMaifest.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:

  1. String Request
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    String url = "https:// string_url/";
    StringRequest
        stringRequest
        = new StringRequest(
            Request.Method.GET,
            url,
            new Response.Listener() {
                @Override
                public void onResponse(String response)
                {
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error)
                {
                }
            });
    requestQueue.add(stringRequest);
    </pre>

    chevron_right

    
    

  2. JSONObject Request
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    String url = "https:// json_url/";
    JsonObjectRequest
        jsonObjectRequest
        = new JsonObjectRequest(
            Request.Method.GET,
            url,
            null,
            new Response.Listener() {
                @Override
                public void onResponse(JSONObject response)
                {
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error)
                {
                }
            });
    requestQueue.add(jsonObjectRequest);

    chevron_right

    
    

  3. JSONArray Request
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    JsonArrayRequest
        jsonArrayRequest
        = new JsonArrayRequest(
            Request.Method.GET,
            url,
            null,
            new Response.Listener() {
                @Override
                public void onResponse(JSONArray response)
                {
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error)
                {
                }
            });
    requestQueue.add(jsonArrayRequest);

    chevron_right

    
    

  4. Image Request
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    int max - width = ...;
    int max_height = ...;
      
    String URL = "http:// image_url.png";
      
    ImageRequest
        imageRequest
        = new ImageRequest(URL,
                           new Response.Listener() {
                               @Override
                               public void
                               onResponse(Bitmap response)
                               {
                                   // Assign the response
                                   // to an ImageView
                                   ImageView
                                       imageView
                                       = (ImageView)
                                           findViewById(
                                               R.id.imageView);
      
                                   imageView.setImageBitmap(response);
                               }
                           },
                           max_width, max_height, null);
      
    requestQueue.add(imageRequest);

    chevron_right

    
    

  5. Adding Post Parameters
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    String tag_json_obj = "json_obj_req";
      
    String
        url
        = "https:// api.xyz.info/volley/person_object.json";
      
    ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...PLease wait");
    pDialog.show();
      
    JsonObjectRequest
        jsonObjReq
        = new JsonObjectRequest(
            Method.POST,
            url,
            null,
            new Response.Listener() {
      
                @Override
                public void onResponse(JSONObject response)
                {
                    Log.d(TAG, response.toString());
                    pDialog.hide();
                }
            },
            new Response.ErrorListener() {
      
                @Override
                public void onErrorResponse(VolleyError error)
                {
                    VolleyLog.d(TAG, "Error: "
                                         + error.getMessage());
                    pDialog.hide();
                }
            }) {
      
              @Override
              protected Map getParams()
              {
                  Map params = new HashMap();
                  params.put("name", "Androidhive");
                  params.put("email", "abc@androidhive.info");
                  params.put("password", "password123");
      
                  return params;
              }
      
          };
      
    AppController.getInstance()
        .addToRequestQueue(jsonObjReq, tag_json_obj);

    chevron_right

    
    

  6. Adding Request Headers
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    String tag_json_obj = "json_obj_req";
      
    String
        url
        = "https:// api.androidhive.info/volley/person_object.json";
      
    ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show();
      
    JsonObjectRequest
        jsonObjReq
        = new JsonObjectRequest(
            Method.POST,
            url,
            null,
            new Response.Listener() {
      
                @Override
                public void onResponse(JSONObject response)
                {
                    Log.d(TAG, response.toString());
                    pDialog.hide();
                }
            },
            new Response.ErrorListener() {
      
                @Override
                public void onErrorResponse(VolleyError error)
                {
                    VolleyLog.d(TAG, "Error: "
                                         + error.getMessage());
                    pDialog.hide();
                }
            }) {
      
              @Override
              public Map getHeaders() throws AuthFailureError
              {
                  HashMap headers = new HashMap();
                  headers.put("Content-Type", "application/json");
                  headers.put("apiKey", "xxxxxxxxxxxxxxx");
                  return headers;
              }
      
          };
      
    AppController.getInstance()
        .addToRequestQueue(jsonObjReq, tag_json_obj);

    chevron_right

    
    

  7. Handling the Volley Cache
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Loading request from cache
    Cache
        cache
        = AppController.getInstance()
              .getRequestQueue()
              .getCache();
      
    Entry entry = cache.get(url);
    if (entry != null) {
        try {
            String
                data
                = new String(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 cache
    AppController.getInstance()
        .getRequestQueue()
        .getCache()
        .invalidate(url, true);
      
    // Turning off cache
    // String request
    StringRequest
        stringReq
        = new StringRequest(....);
      
    // 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);

    chevron_right

    
    

  8. Cancelling Request
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  9. Request Prioritization
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    private Priority priority = Priority.HIGH;
      
    StringRequest
        strReq
        = new StringRequest(
            Method.GET,
            Const.URL_STRING_REQ,
            new Response
                .Listener() {
       
                        @Override
                        public void onResponse(String response) {
      
                            Log.d(TAG, response.toString());
                            msgResponse.setText(response.toString());
                            hideProgressDialog();
       
                        } },
            new Response
                .ErrorListener() {
       
                        @Override
                        public void 
                        onErrorResponse(VolleyError error) {
      
                            VolleyLog.d(TAG, 
                                        "Error: " 
                                            + error.getMessage());
                            hideProgressDialog();
                        } }) {
      
              @Override
              public Priority getPriority()
              {
                  return priority;
              }
      
          };

    chevron_right

    
    



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.