Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Android Volley Tutorial


Using Volley for Networking in Android Applications.

Volley is an HTTP library developed by Google to ease networking tasks in Android Applications. Volley supersedes Java’s java.net.HttpURLConnection class and Apache’s org.apache.http.client in handling network requests. Volley can handle almost each and everything you will need to do over the network, it handles HTTP request and also manages the async tasks that you need to use while working with canonical networking classes.

Features of Android Volley Library :-

  1. Volley manages network request automatically and without you using any AsyncTask. It offers multiple concurrent network connections, resulting in faster and efficient network operations.
  2. Volley caches all network requests, utilizing the previous results in the case of change in activity configuration. However due to the same reason, it is only good for small Volley and not suitable for large download or streaming operations.
  3. It has a powerful cancellation API. You can fully control the request cancellation , or you can set blocks or scopes of requests to cancel.
  4. Volley allows you to control and order the network requests making it easy to populate UI elements in an orderly manner , useful in case of social networking apps like facebook , twitter. It also provides support for request prioritization.
  5. Volley has built in debugging and tracing tools which allow user to get to the root of the error.

Working of Volley.

While using volley you are only concerned about adding a Request to the queue, handling it’s response, and you can actually ignore everything that is running in the background. When you fire a network request it is added to cache queue in the priority order. A cache dispatcher thread figures out whether it can service the request entirely from the cache or it needs to fire a network request for the response. In the case of a cache miss or if cached response has expired, the network dispatcher services the request, handles the parsing of the response and returns the response back to the main thread.

Volley is very useful for network request involving strings, images, and JSON. It has built in support for these objects.

We will now show you how to use Volley for networking in android apps. We have created a Demo app which downloads the String, JsonObject, JsonArray and Image Object from the following URL’s respectively.

String URL http://androidtutorialpoint.com/api/volleyString
JsonObject URL http://androidtutorialpoint.com/api/volleyJsonObject
JsonArray URL http://androidtutorialpoint.com/api/volleyJsonArray
Image URL http://androidtutorialpoint.com/api/lg_nexus_5x

On completion the app will show user a menu, where she can select the type of response she wants as shown in the figure below.

Android Volley Tutorial Menu

The User can select one of the menu options and based upon her choice the response will be shown in a dialog box. You will get the following response if you click the four buttons respectively.

Volley Response on Clicking the Menu Options





Pre-requisites

  1. Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
  2. A real time android device (Smartphone or Tablet) configured with Android Studio. .
  3. Basic knowledge of JSON Parsing, Refer to JSON Parsing Tutorial. to learn about parsing JSON response.

Creating a New Project and Adding Volley

  1. Go to File → New → New Project and enter your Application Name.
  2. Enter Company Domain, this is used to uniquely identify your App’s package worldwide.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have left Activity Name as MainActivity.
  5. Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.
  6. To add Volley to your project add the following dependency in your App’s build.gradle file.
  7. compile 'com.android.volley:volley:1.0.0'
    

Add Internet Permission

Add the following permission to your AndroidManifest.xml file

AndroidManifest.xml

Setup Request Queue

The most efficient way to use Volley for a network intensive android application is to create a Singleton pattern and set up a single object of RequestQueue for the complete lifecycle of your app. To achieve this we will create a singleton class and add RequestQueue object as member field and create methods to achieve the functionality offered by Volley.
Create a new java class AppSingleton.java and add the following code :

AppSingleton.java

    package com.androidtutorialpoint.volleytutorial;

    import android.content.Context;
    import android.graphics.Bitmap;
    import android.util.LruCache;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.toolbox.ImageLoader;
    import com.android.volley.toolbox.Volley;

    /**
     * Created by androidtutorialpoint on 5/11/16.
     */
    public class AppSingleton {
        private static AppSingleton mAppSingletonInstance;
        private RequestQueue mRequestQueue;
        private ImageLoader mImageLoader;
        private static Context mContext;

        private AppSingleton(Context context) {
            mContext = context;
            mRequestQueue = getRequestQueue();

            mImageLoader = new ImageLoader(mRequestQueue,
                    new ImageLoader.ImageCache() {
                        private final LruCache
                                cache = new LruCache(20);

                        @Override
                        public Bitmap getBitmap(String url) {
                            return cache.get(url);
                        }

                        @Override
                        public void putBitmap(String url, Bitmap bitmap) {
                            cache.put(url, bitmap);
                        }
                    });
        }

        public static synchronized AppSingleton getInstance(Context context) {
            if (mAppSingletonInstance == null) {
                mAppSingletonInstance = new AppSingleton(context);
            }
            return mAppSingletonInstance;
        }

        public RequestQueue getRequestQueue() {
            if (mRequestQueue == null) {
                // getApplicationContext() is key, it keeps you from leaking the
                // Activity or BroadcastReceiver if someone passes one in.
                mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
            }
            return mRequestQueue;
        }

        public  void addToRequestQueue(Request req,String tag) {
            req.setTag(tag);
            getRequestQueue().add(req);
        }

        public ImageLoader getImageLoader() {
            return mImageLoader;
        }

        public void cancelPendingRequests(Object tag) {
            if (mRequestQueue != null) {
                mRequestQueue.cancelAll(tag);
            }
        }
    }

We have created an instance of type AppSingleton and made the constructor private to apply singleton pattern. Additionally we have instances of RequestQueue and ImageLoader. We have also added getter methods for RequestQueue and ImageLoader. In the getRequestQueue() method we check whether the object already exists, if not we use the convenience method Volley.newRequestQueue(), pass in the application context and return the RequestQueue reference.

The method addToRequestQueue() takes in a generic Type and adds it to request queue. In the constructor, we create an ImageLoader object using the RequestQueue object and a new ImageCache object.

ImageCache is a cache adapter interface. It is used as an L1 cache before dispatch to Volley. We add a LruCache object from package java.util.LruCache and implement the interface methods getBitmap() and putBitmap().

cancelPendingRequests() is used to cancel a request using a tag.

To work with volley you construct a request object, there are different kinds of requests objects that you can use, most important ones are StringRequest, JsonObjectRequest, JsonArrayRequest and ImageRequest. Let’s review how to perform these network requests one by one.

String Request using Volley

In the MainActivity.java, create the following method to make a Volley request for String Object.

MainActivity.java

public void volleyStringRequst(String url){

        String  REQUEST_TAG = "com.androidtutorialpoint.volleyStringRequest";
        progressDialog.setMessage("Loading...");
        progressDialog.show();

        StringRequest strReq = new StringRequest(url, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, response.toString());

                LayoutInflater li = LayoutInflater.from(MainActivity.this);
                showDialogView = li.inflate(R.layout.show_dialog, null);
                outputTextView = (TextView)showDialogView.findViewById(R.id.text_view_dialog);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
                alertDialogBuilder.setView(showDialogView);
                alertDialogBuilder
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        })
                        .setCancelable(false)
                        .create();
                outputTextView.setText(response.toString());
                alertDialogBuilder.show();
                progressDialog.hide();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                progressDialog.hide();
            }
        });
        // Adding String request to request queue
        AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, REQUEST_TAG);
    }

The REQUEST_TAG is used to cancel the request. We have created a new StringRequest Object, the constructor takes in three arguments.

  1. Url: the URL for the network request.
  2. Listener Object: anonymous inner type, an implementation of Response.Listener(), It has an onRespose method which will receive the string from the web.
  3. ErrorListener Object: anonymous inner type , an implementaion of onErrorResponse(VolleyError err) will get an instance of object of Volley Error
  4. In the onResponse() method, we are logging the output to LogCat and also showing the response recieved in an AlertDialog.
    In the onErrorResponse() method, we are simply logging the error message to LogCat.

    Now that we have described the network request, We need to add the request to a queue, We get the instance of the RequestQueue from AppSingleton and add our request to the queue.

    Next, create the following function to make a Volley request for JSONObject.

    MainActivity.java

    public void volleyJsonObjectRequest(String url){
    
            String  REQUEST_TAG = "com.androidtutorialpoint.volleyJsonObjectRequest";
            progressDialog.setMessage("Loading...");
            progressDialog.show();
    
            JsonObjectRequest jsonObjectReq = new JsonObjectRequest(url, null,
                    new Response.Listener() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d(TAG, response.toString());
    
                            LayoutInflater li = LayoutInflater.from(MainActivity.this);
                            showDialogView = li.inflate(R.layout.show_dialog, null);
                            outputTextView = (TextView)showDialogView.findViewById(R.id.text_view_dialog);
                            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
                            alertDialogBuilder.setView(showDialogView);
                            alertDialogBuilder
                                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                        }
                                    })
                                    .setCancelable(false)
                                    .create();
                            outputTextView.setText(response.toString());
                            alertDialogBuilder.show();
                            progressDialog.hide();
    
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    progressDialog.hide();
                }
            });
    
            // Adding JsonObject request to request queue
            AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectReq,REQUEST_TAG);
        }
    

    This method is similar to volleyStringRequest() method. Here we are creating JsonObjectRequest instead and the response listener expects a JsonObject.

    Next, create the following method to make a Volley request for JSONArray.

    MainActivity.java

        public void volleyJsonArrayRequest(String url){
    
            String  REQUEST_TAG = "com.androidtutorialpoint.volleyJsonArrayRequest";
            progressDialog.setMessage("Loading...");
            progressDialog.show();
    
            JsonArrayRequest jsonArrayReq = new JsonArrayRequest(url,
                    new Response.Listener() {
                        @Override
                        public void onResponse(JSONArray response) {
                            Log.d(TAG, response.toString());
                            LayoutInflater li = LayoutInflater.from(MainActivity.this);
                            showDialogView = li.inflate(R.layout.show_dialog, null);
                            outputTextView = (TextView)showDialogView.findViewById(R.id.text_view_dialog);
                            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
                            alertDialogBuilder.setView(showDialogView);
                            alertDialogBuilder
                                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                        }
                                    })
                                    .setCancelable(false)
                                    .create();
                            outputTextView.setText(response.toString());
                            alertDialogBuilder.show();
                            progressDialog.hide();                    }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    progressDialog.hide();
                }
            });
    
            // Adding JsonObject request to request queue
            AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonArrayReq, REQUEST_TAG);
        }
    

    Here we are creating a JsonArray request and the response listener expects a JSONArray Object.
    Next, we create the a function to make a Volley request for getting Images over network.

    MainActivity.java

    public void volleyImageLoader(String url){
            ImageLoader imageLoader = AppSingleton.getInstance(getApplicationContext()).getImageLoader();
    
                imageLoader.get(url, new ImageLoader.ImageListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Image Load Error: " + error.getMessage());
                }
    
                @Override
                public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
                    if (response.getBitmap() != null) {
    
                        LayoutInflater li = LayoutInflater.from(MainActivity.this);
                        showDialogView = li.inflate(R.layout.show_dialog, null);
                        outputImageView = (ImageView)showDialogView.findViewById(R.id.image_view_dialog);
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
                        alertDialogBuilder.setView(showDialogView);
                        alertDialogBuilder
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                    }
                                })
                                .setCancelable(false)
                                .create();
                        outputImageView.setImageBitmap(response.getBitmap());
                        alertDialogBuilder.show();
                    }
                }
            });
        }
    

    We get the ImageLoader instance from the AppSingleton and use its get() method to download the image. The get() method of ImageLoader has onResponse() method to handle the response. The return type of the method is an ImageContainer object, for demo purpose we are simply showing the images in AlertDialog.

    Volley has additional method to handle the cache. We will describe these methods briefly.

         
    public void volleyCacheRequest(String url){
            Cache cache = AppSingleton.getInstance(getApplicationContext()).getRequestQueue().getCache();
            Cache.Entry reqEntry = cache.get(url);
            if(reqEntry != null){
                try {
                    String data = new String(reqEntry.data, "UTF-8");
                    //Handle the Data here.
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            else{
    
                //Request Not present in cache, launch a network request instead.
            }
        }
    
        public void volleyInvalidateCache(String url){
            AppSingleton.getInstance(getApplicationContext()).getRequestQueue().getCache().invalidate(url, true);
        }
    
        public void volleyDeleteCache(String url){
            AppSingleton.getInstance(getApplicationContext()).getRequestQueue().getCache().remove(url);
        }
    
        public void volleyClearCache(){
            AppSingleton.getInstance(getApplicationContext()).getRequestQueue().getCache().clear();
        }
    

    The volleyCacheRequest() checks for the request entry in the cache, if the request is already present then you can handle the data accordingly and in case the data is not present, then launch a network request to get data from network.

    ThevolleyInvalidateCache() is used to invalidate the existing cache for particular entry and volleyDeleteCache() is used to delete cache for particular url.

    ThevolleyClearCache() will be used to clear the entire cache.

    Please find the complete Code for MainActivity.java here => MainActivity.java
    Moreover the layout consist of 4 buttons for String, JsonObject, JsonArray and Image Response. Open activity_main.xml and put the code from the following file => activity_main.xml
    The DialogAlert which is shown in the Demo app consist of TextView and ImageView to show the response. Create a new Layout file show_dialog.xml and put the following code.

    show_dialog.xml




    What’s Next?

    With the knowledge of how to use volley in Android Applications, you can experiment with different API’s available on the internet, parse them and create beautiful android applications. We will soon be covering one such post on how to use TMDB’s (The Movie DataBase) API using Volley and display the movies in a grid view.

    Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

    Click on Download Now button to download the full code.



    CodeProject

    The post Android Volley Tutorial appeared first on Android Tutorial Point.



This post first appeared on Android Tutorial Point, please read the originial post: here

Share the post

Android Volley Tutorial

×

Subscribe to Android Tutorial Point

Get updates delivered right to your inbox!

Thank you for your subscription

×