Android – Volley library example

By -

Android volley, volley

I am not sure whether you have heard “Volley” word yet but it’s the library on which one expert talk was delivered during Google I/O 2013 by Ficus Kirkpatrick.

What is Volley library exactly for?

Volley is a library that makes networking for Android apps easier and most importantly, faster.

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. And one more benefit of having less code is less number of bugs and that’s all developers want and aim for :)

My mean of writing the same network call code is AsyncTask and the logic/code you write for fetching response from Web API and displaying it in particular View. We have to take care of displaying ProgressBar/ProgressDialog inside onPreExecute() and onPostExecute(). I know this is not a hard task but still boring, sometimes I also feel get bored even though I have defined BaseTask class for managing display/dismiss operation of ProgressBar/ProgressDialog and many more thing. So now we can say Volley can be a powerful alternative of AsyncTask.

Advantages of using Volley:

  1. Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.
  2. Volley provides transparent disk and memory caching.
  3. Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel.
  4. Volley provides powerful customization abilities.
  5. Volley provides Debugging and tracing tools

How to get started?

  1. Clone the Volley project
  2. Import the code into your project

Clone the Volley project:

git clone https://android.googlesource.com/platform/frameworks/volley

git

It has created “Volley” folder :) Now we have to import this in eclipse or Android studio. FYI, I have been using Git GUI client on my windows machine.

Now suppose If your machine is not having Git client installed and still want to clone repository then Eclipse and ADT Bundle is having option for you to clone repository and import project directly. Refer my previous article for the same: Android – Import projects from Git

2 Main classes of Volley:

There are 2 main classes:
1. Request queue
2. Request

Request queue: It is the interest you use for dispatching requests to the network, you can make a request queue on demand if you want, but typically, you’ll instead create it early on, at startup time, and keep it around and use it as a Singleton.

Request: It contains all the necessary details for making web API call. For example: which method to Use (GET or POST), request data to pass, response listener, error listener.

Take a look at JSONObjectRequest request method:

JsonObjectRequest Volley

Basic example using Volley:

I assume you have already cloned/downloaded Volley library from git repo. Now, follow the steps to create a simple example of fetching tweets and display it into ListView.

Step 1: Make sure you have imported Volley projects into Eclipse, if you haven’t then import it. Now after importing, we need to make it a Library project by Right click => Properties => Android (left panel).

volley as a library project

Step 2: Now, Create a new project with the name VolleyExample.
Step 3: Right click on VolleyExample and Include Volley Library in our project.

Including volley library in Android project

Step 4: Include INTERNET permission inside AndroidManifest.xml file.

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

Step 5:

i) Create an object of RequestQueue class.

RequestQueue queue = Volley.newRequestQueue(this);

ii) Create a JSONObjectRequest with response and error listener.

String url = "https://www.googleapis.com/customsearch/v1?key=AIzaSyBmSXUzVZBKQv9FJkTpZXn0dObKgEQOIFU&cx=014099860786446192319:t5mr0xnusiy&q=AndroidDev&alt=json&searchType=image";

JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

		@Override
		public void onResponse(JSONObject response) {
			// TODO Auto-generated method stub
			txtDisplay.setText("Response => "+response.toString());
			findViewById(R.id.progressBar1).setVisibility(View.GONE);
		}
	}, new Response.ErrorListener() {

		@Override
		public void onErrorResponse(VolleyError error) {
		// TODO Auto-generated method stub

		}
	});

iii) Add your request into the RequestQueue.

queue.add(jsObjRequest);

Complete Code of MainActivity.java file:

package com.technotalkative.volleyexamplesimple;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends Activity {

	private TextView txtDisplay;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		txtDisplay = (TextView) findViewById(R.id.txtDisplay);

		RequestQueue queue = Volley.newRequestQueue(this);
		String url = "https://www.googleapis.com/customsearch/v1?key=AIzaSyBmSXUzVZBKQv9FJkTpZXn0dObKgEQOIFU&cx=014099860786446192319:t5mr0xnusiy&q=AndroidDev&alt=json&searchType=image";

		JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject response) {
				// TODO Auto-generated method stub
				txtDisplay.setText("Response => "+response.toString());
				findViewById(R.id.progressBar1).setVisibility(View.GONE);
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub

			}
		});

		queue.add(jsObjRequest);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

Download Volley library and sample example: https://github.com/PareshMayani/Android-Volley-Example

Video in case you haven missed session: Google I/O 2013 – Volley: Easy, Fast Networking for Android

Paresh Mayani

Paresh Mayani is a lead android developer from India. Currently, He is Sr. Software engineer at InfoStretch Solutions Pvt. Ltd. He has been developing android apps since very 1st version i.e. Android 1.5, he says he has seen days and nights of Android history. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

  • Anoop CH

    Shouldn’t this network action done inside AsyncTask?

    • http://tasomaniac.com Said Tahsin Dane

      Network actions should be done in background thread. ASyncTask does this. Volley is new and does the same thing in a better way.

      • Anoop CH

        I am asking is there a need to write the above code inside an Asynctask?

        • http://www.technotalkative.com/ Paresh Mayani

          Some where in article I have written Volley can be a powerful alternative of AsyncTask. ;)

        • http://tasomaniac.com Said Tahsin Dane

          No don’t do that. The above code works as it is.

  • Anoop CH

    Ah.. Found it.

    Thanks for the point. I was going through the code and getting started. Skipped the intro…

    :-)

  • mortenslotthansen

    Good post. Have you found a way to cancel all image requests triggered by activity A when moving to activity B ? In the current implementation there is no TAG set for image requests thus making this impossible. I myself is changing the NetworkImageView to pass the activity name as the TAG allowing me to cancel requests when leaving the activity.

  • Hardik Suba

    Nice post. I followed your steps and clone project from Git to eclipse, but I’m not able to add it as a library project.
    Any idea?

  • Chandan Gupta

    hi…

    Paresh ,is it possible to upload images and videos using this library
    If yes then how ?

  • Dwivedi Ji

    I try this API, but right now I am not getting any difference with it and Asynctask, Both take same time to complete task and get response, So what are the benefit of this Library over the Asynctask.

    • http://www.technotalkative.com/ Paresh Mayani

      I hope you know about executing AsyncTask in newer version > Honeycomb. Have you noticed that difference and fact?

      • Dwivedi Ji

        Yes, I hope you talking about executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) method of AsyncTask. So can you please elaborate this, How this api be helpful over version Honeycomb

  • John Matta

    I tried everything like the example but it keeps showing the progress bar loading and nothing appears at all!!