Main navigation

Android Volley Tutorial

adsense

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

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

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<String, Bitmap>
                                cache = new LruCache<String, Bitmap>(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 <T> void addToRequestQueue(Request<T> 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<String>() {
            @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<JSONObject>() {
                        @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<JSONArray>() {
                        @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

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
        android:id="@+id/layout_root"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="5dp" >
    
        <TextView
            android:id="@+id/text_view_dialog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:textAlignment="center"
            android:gravity="center"
            style="@android:style/TextAppearance.DeviceDefault.Widget.ActionBar.Menu"
            />
    
        <ImageView
            android:id="@+id/image_view_dialog"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
    </LinearLayout>
    




    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.

    Android Tutorial Point Download Now



Reader Interactions

Comments

  1. When I was searching on google and I found your blog at 1st position. After reading this article, I realised that your blog deserves 1st place on the google.

    Thanks

  2. Great Tutorial!

    Two points:

    1.) You have to register the pattern in the Manifest

    2.) Maybe the array loop is missing for the array objects. Better for understanding!

  3. I am truly delighted to glance at this weblog posts which consists of tons oof useful data,
    thanks for providing these kinds of information.

  4. when i test this URL in browser it work ,but at android App not work ,however when i change it with my API it work ,why this URLs not work at APP. thanks.

Trackbacks

  1. imitazione cartier anello in oro rosa

    Howdy! I could have sworn I’ve been to this blog before but after looking at some of the posts I realized it’s new to me. Regardless, I’m certainly delighted I discovered it and I’ll be book-marking it and checking back often!

Leave a Reply

Advertisment ad adsense adlogger