Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don’t have to worry about using asynctask anymore.

Volley comes with lot of features. Some of them are

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

Before getting into this tutorial, I suggested you to view the below presentation by Ficus Kirkpatrick at Google I/O to get an overview of volley.

android volley library tutorial

1. Creating New Project

1. In Android Studio, create a new project by navigating to File ⇒ New Project and fill all the required details. When it prompts to select a default activity, select Blank Activity and proceed.

2. Create two packages named app and utils to keep the project organized.

3. Open build.gradle and add volley support by adding
compile ‘com.mcxiaoke.volley:library-aar:1.0.0’ under dependencies section.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.volley:volley:1.0.0'
}

1.1 Creating Volley Singleton Class

The best way to maintain volley core objects and request queue is, making them global by creating a singleton class which extends Application object.

4. Under utils package, create a class named LruBitmapCache.java and paste the below code. This class is required to handle image cache.

package info.androidhive.volleyexamples.volley.utils;

import com.android.volley.toolbox.ImageLoader.ImageCache;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements
		ImageCache {
	public static int getDefaultLruCacheSize() {
		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
		final int cacheSize = maxMemory / 8;

		return cacheSize;
	}

	public LruBitmapCache() {
		this(getDefaultLruCacheSize());
	}

	public LruBitmapCache(int sizeInKiloBytes) {
		super(sizeInKiloBytes);
	}

	@Override
	protected int sizeOf(String key, Bitmap value) {
		return value.getRowBytes() * value.getHeight() / 1024;
	}

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

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

5. Under app package, create a class name AppController.java and extend the class from Application and add the following code.

package info.androidhive.volleyexamples.app;

import info.androidhive.volleyexamples.volley.utils.LruBitmapCache;
import android.app.Application;
import android.text.TextUtils;

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

public class AppController extends Application {

	public static final String TAG = AppController.class
			.getSimpleName();

	private RequestQueue mRequestQueue;
	private ImageLoader mImageLoader;

	private static AppController mInstance;

	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;
	}

	public static synchronized AppController getInstance() {
		return mInstance;
	}

	public RequestQueue getRequestQueue() {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		}

		return mRequestQueue;
	}

	public ImageLoader getImageLoader() {
		getRequestQueue();
		if (mImageLoader == null) {
			mImageLoader = new ImageLoader(this.mRequestQueue,
					new LruBitmapCache());
		}
		return this.mImageLoader;
	}

	public <T> void addToRequestQueue(Request<T> req, String tag) {
		// set the default tag if tag is empty
		req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
		getRequestQueue().add(req);
	}

	public <T> void addToRequestQueue(Request<T> req) {
		req.setTag(TAG);
		getRequestQueue().add(req);
	}

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

6. Now open AndroidManifest.xml and add this singleton class in <application> tag using android:name property to execute the class automatically whenever app launches. Also add INTERNET permission as we are going to make network calls.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.volleyexamples"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

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

    <application
        android:name="info.androidhive.volleyexamples.app.AppController"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!-- all activities and other stuff -->
    </application>

</manifest>

Now the primary setup required for volley is done. Let’s move on to individual options those volley provides to make the http requests.

2. Making JSON request

Volley provides an easy to make json requests. If you are expecting json object in the response, you should use JsonObjectRequest class or if the response is json array, JsonArrayRequest class should be used.

2.1 Making json object request
Following code will make a json object request where the json response will start with object notation ‘{

// Tag used to cancel the request
String tag_json_obj = "json_obj_req";

String url = "http://api.androidhive.info/volley/person_object.json";
		
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();		
		
		JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
				url, null,
				new Response.Listener<JSONObject>() {

					@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());
						// hide the progress dialog
						pDialog.hide();
					}
				});

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

2.2 Making json array request
Following will make json array request where the json response starts with array notation ‘[

// Tag used to cancel the request
String tag_json_arry = "json_array_req";

String url = "http://api.androidhive.info/volley/person_array.json";
		
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();		
		
JsonArrayRequest req = new JsonArrayRequest(url,
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray 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();
					}
				});

// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_json_arry);

3. Making String request

StringRequest class will be used to fetch any kind of string data. The response can be json, xml, html or plain text.

// Tag used to cancel the request
String  tag_string_req = "string_req";

String url = "http://api.androidhive.info/volley/string_response.html";
		
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();		
		
StringRequest strReq = new StringRequest(Method.GET,
				url, new Response.Listener<String>() {

					@Override
					public void onResponse(String 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();
					}
				});

// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

4. Adding post parameters

It is obvious that sometimes we need to submit request parameters while hitting the url. To do that we have to override getParams() method which should return list of parameters to be send in a key value format.

If you observe below example, I am submitting name, email and password as request parameters.

// Tag used to cancel the request
String tag_json_obj = "json_obj_req";

String url = "http://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<JSONObject>() {

					@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<String, String> getParams() {
				Map<String, String> params = new HashMap<String, String>();
				params.put("name", "Androidhive");
				params.put("email", "abc@androidhive.info");
				params.put("password", "password123");

				return params;
			}

		};

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

5. Adding request headers

Just like adding request parameters, to send request headers, we have to override getHeaders(). In below example I am sending Content-Type and apiKey in request headers.

// Tag used to cancel the request
String tag_json_obj = "json_obj_req";

String url = "http://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<JSONObject>() {

					@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();
					}
				}) {

			/**
			 * Passing some request headers
			 * */
			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				HashMap<String, String> headers = new HashMap<String, String>();
				headers.put("Content-Type", "application/json");
				headers.put("apiKey", "xxxxxxxxxxxxxxx");
				return headers;
			}

		};

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

6. Making Image request

Volley introduced custom image view element called NetworkImageView to display the images from an URL. Previously downloading images and maintaining caches is a tough job. Now using volley this can be done with very few lines of code.

6.1 Loading image in NetworkImageView
Following will load an image from an URL into NetworkImageView.

ImageLoader imageLoader = AppController.getInstance().getImageLoader();

// If you are using NetworkImageView
imgNetWorkView.setImageUrl(Const.URL_IMAGE, imageLoader);

6.2 Loading image in ImageView
If you want to load image into ImageView instead of NetworkImageView, you can do that too as mentioned below. Here we will have success and error callbacks, you have to take appropriate action depending on the need. Below in onResponse() method using response.getBitmap() I am loading bitmap into an ImageView.

		ImageLoader imageLoader = AppController.getInstance().getImageLoader();

		// If you are using normal ImageView
		imageLoader.get(Const.URL_IMAGE, new ImageListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e(TAG, "Image Load Error: " + error.getMessage());
			}

			@Override
			public void onResponse(ImageContainer response, boolean arg1) {
				if (response.getBitmap() != null) {
					// load image into imageview
					imageView.setImageBitmap(response.getBitmap());
				}
			}
		});

6.3 Defining placeholder image and error image
Here is another way of displaying image into ImageView with the option of placeholder for loader and error. The loader placeholder will be displayed until the image gets downloaded. If the image fails to download, the error placeholder will be displayed.

// Loading image with placeholder and error image
imageLoader.get(Const.URL_IMAGE, ImageLoader.getImageListener(
				imageView, R.drawable.ico_loading, R.drawable.ico_error));

7. Handling the volley Cache

Volley comes with powerful cache mechanism to maintain request cache. This saves lot of internet bandwidth and reduces user waiting time. Following are few example of using volley cache methods.

7.1 Loading request from cache
Like below you can check for a cached response of an URL before making a network call.

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{
	// Cached response doesn't exists. Make network call here
}

7.2 Invalidate cache
Invalidate means we are invalidating the cached data instead of deleting it. Volley will still uses the cached object until the new data received from server. Once it receives the response from the server it will override the older cached response.

AppController.getInstance().getRequestQueue().getCache().invalidate(url, true);

7.3 Turning off cache
If you want disable the cache for a particular url, you can use setShouldCache() method as below.

// String request
StringRequest stringReq = new StringRequest(....);

// disable cache
stringReq.setShouldCache(false);

7.4 Deleting cache for particular URL
Use remove() to delete cache of an URL.

AppController.getInstance().getRequestQueue().getCache().remove(url);

7.5 Deleting all the cache
Followoing will delete the cache for all the URLs.

AppController.getInstance().getRequestQueue().getCache().clear(url);

8. Cancelling requests

If you notice addToRequestQueue(request, tag) method, it accepts two parameters. One is request object and other is request tag. This tag will be used to identify the request while cancelling it. If the tag is same for multiple requests, all the requests will be cancelled. cancellAll() method is used to cancel any request.

8.1 Cancel single request
Following will cancel all the request with the tag named “feed_request”

String tag_json_arry = "json_req";
ApplicationController.getInstance().getRequestQueue().cancelAll("feed_request");

8.2 Cancel all requests
If you don’t pass any tag to cancelAll() method, it will cancel the request in request queue.

ApplicationController.getInstance().getRequestQueue().cancelAll();

9. Request prioritization

If you are making multiple request at the same time, you can prioritize the requests those you want be executed first. The priory can be Normal, Low, Immediate and High.

private Priority priority = Priority.HIGH;

StringRequest strReq = new StringRequest(Method.GET,
				Const.URL_STRING_REQ, new Response.Listener<String>() {

					@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;
			}

		};

Missing! Making XML request

As of now volley doesn’t provided any native classes to make XML requests, but this can be achieved by building a custom xml wrapper class by utilizing volley’s customization capabilities. The part of writing xml parser using volley will be covered in upcoming tutorial.

I have given a sample project covering the scenarios explained in this tutorial. Download it and let’s discuss the queries if you have any in the comments section 🙂

Change Log

Updated On 31st Aug, 2015 (Added Android Studio Support)
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Nice article..

  • oplog

    Goodyear tutoriel, I like Volley. but I Wonder how to make a request longer. i.e sometimes the request run Just a few second and it’ not always What we want. how can one prolong it?

    • Ngô Văn Bằng

      it mean many request ? .

    • Why do you want a prolong request?

  • Can

    Great post! I’m waiting for XML parsing using Volley.

  • Tarik Laila

    thanks

  • Nitin Misra

    how can i check whether the request queue is empty or not, i want sequential calls to RequestQueue

  • Trần Minh Thuận

    Very nice. Thanks

  • yeah1boy

    Method.POST in Json request not suscessfull! it haven’t in sample project

  • Satyaki Mukherjee

    All is fine for me as per your give tutorial but when write this at command line, it return this and does not create any volley.jar file :

    D:worksSatyakiRnDVolley Librarygitvolley>ant jar

    Unable to locate tools.jar. Expected to find it in C:Program FilesJavajre7libtools.jar

    Buildfile: D:worksSatyakiRnDVolley Librarygitvolleybuild.xml

    -pre-build:

    -check-env:

    [checkenv] Android SDK Tools Revision 22.3.0

    [checkenv] Installed at E:Android Softwareadt-bundle-windows-x86-20130917sdk

    -setup:

    [echo] Project Name: volley

    [gettype] Project Type: Application

    -build-setup:

    [getbuildtools] Using latest Build Tools: 19.0.1

    [echo] Resolving Build Target for volley…

    [gettarget] Project Target: Android 4.4.2

    [gettarget] API level: 19

    [echo] ———-

    [echo] Creating output directories if needed…

    [mkdir] Created dir: D:worksSatyakiRnDVolley Librarygitvolleyres

    [mkdir] Created dir: D:worksSatyakiRnDVolley Librarygitvolleylibs

    [mkdir] Created dir: D:worksSatyakiRnDVolley Librarygitvolleybin

    [mkdir] Created dir: D:worksSatyakiRnDVolley Librarygitvolleybinres

    [mkdir] Created dir: D:worksSatyakiRnDVolley LibrarygitvolleybinrsObj

    [mkdir] Created dir: D:worksSatyakiRnDVolley LibrarygitvolleybinrsLibs

    [mkdir] Created dir: D:worksSatyakiRnDVolley Librarygitvolleygen

    [mkdir] Created dir: D:worksSatyakiRnDVolley Librarygitvolleybinclasses

    [mkdir] Created dir: D:worksSatyakiRnDVolley LibrarygitvolleybindexedLibs

    [echo] ———-

    [echo] Resolving Dependencies for volley…

    [dependency] Library dependencies:

    [dependency] No Libraries

    [dependency]

    [dependency] ——————

    [echo] ———-

    [echo] Building Libraries with ‘${build.target}’…

    [subant] No sub-builds to iterate on

    -code-gen:

    [mergemanifest] Merging AndroidManifest files into one.

    [mergemanifest] Manifest merger disabled. Using project manifest only.

    [echo] Handling aidl files…

    [aidl] No AIDL files to compile.

    [echo] ———-

    [echo] Handling RenderScript files…

    [echo] ———-

    [echo] Handling Resources…

    [aapt] Generating resource IDs…

    [echo] ———-

    [echo] Handling BuildConfig class…

    [buildconfig] Generating BuildConfig class.

    -pre-compile:

    -compile:

    BUILD FAILED

    E:Android Softwareadt-bundle-windows-x86-20130917sdktoolsantbuild.xml:720: The following error occurred w

    hile executing this line:

    E:Android Softwareadt-bundle-windows-x86-20130917sdktoolsantbuild.xml:734: Unable to find a javac compile

    r;

    com.sun.tools.javac.Main is not on the classpath.

    Perhaps JAVA_HOME does not point to the JDK.

    It is currently set to “C:Program FilesJavajre7”

    Total time: 0 seconds

    D:worksSatyakiRnDVolley Librarygitvolley>

    Please help me Ravi. Thanks for such a nice tutorial .

    • You have to set JAVA_HOME in environmental variables to your java/jdk folder. You should able to execute javac in command prompt.

  • forall02

    I use android update project -p . But error ‘android’ is not recognized as an internal or external command

    • forall02

      please help me

      • Keep android-sdk-windowstools in your Environmental variables.

  • EnvyAndroid

    Would this be usable in a listadapter, for dynamically loading images?

  • akhil nair

    hi Ravi good article i have a query how can we pass params/header

  • kady

    Hi ravi how can we get the json with php?
    I try to get the json and write it to a file but the content is not shown.
    Here is my code please can you help me
    {‘Nom’}.”‘, ‘”.$obj->{‘Prenom’}.”‘)”;
    file_put_contents($file, $current);

    $posts = array(1);
    header(‘Content-type: application/json’);
    echo json_encode(array(‘posts’=>$posts));

    ?>

  • MRX

    Hi Ravi thanks for such a nice tutorial. Can you also provide the tutorial for using other networking libraries such as RoboSpice, retrofit etc.?

  • Louis

    Hi Ravi, can you also make a tutorial about how to implement Retrofit? http://square.github.io/retrofit/
    It seem alot more easier but i duno how…thanks in advance

  • Guest

    Gooooooooob tutotial Ravi 😀

  • VLEIX

    Goooooooood tutotial Ravi 😀

  • Good tuturial Ravi but mine doesn’t accept the post paremeters when i use the jsonObject request but works well when i use stringRequest.

  • Can

    Hi, how can I send url-encoded parameters with GET request?

    For example I’d like to use Parse REST API like below,

    curl -X GET

    -H “X-Parse-Application-Id: ………………………………………………”

    -H “X-Parse-REST-API-Key: ………………………………………………..”

    -G

    –data-urlencode ‘username=cooldude6’

    –data-urlencode ‘password=p_n7!-e8’

    https://api.parse.com/1/login

    How can I implement this?

  • Naik

    Good tutorial, Ravi. But i have a different kind of requirement. In my case, volley should route its request via a specified proxy. Currently, i see that Volley accepts only URL as the input. Is there any way wherein we can make Volley accept proxyhost and proxyport and route this request via the proxy ? Does volley support proxy servers ?

  • Guest

    How to set session cookies using Volley Library

  • Guest

    Great tutorial!!works like charm!!

  • Vineel Sadineni

    Great tutorial!! works like a charm!!

  • diegoPy

    Great one Androidhive!

  • Guest

    Nice Tutorial.. Really Helpful. But I got a problem with my project, i want to sort the listview according to the data, i actually done that with Async task, I am new to volley, so can u please help me.. I want to sort the listview according to the text.. Please help me Ravi …

    • Edwiin Sandoval

      Maybe you can use a ArrayList and sort the array before printing in the list view component !!!

  • Siddiq

    Is there any other networking library other than Volley.

  • Ravi

    Great Tutorial, it will be really help if you can show us how to fill listview to json request

    • bradhawk

      I got working example of what you need, just check it :
      http://pastebin.com/LiqRudBB

      sorry for messy code, hope you can learn something from the code.

    • bradhawk

      Hi,
      I got working example for what you need, just check it out :
      http://pastebin.com/LiqRudBB

      Sorry for messy code, hope you can learn something from the code.

  • bradhawk

    Hi Ravi, great tutorial.

    I got a problem using :
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

    the program immediately closed, but when I using :
    private RequestQueue mRequestQueue;
    mRequestQueue = Volley.newRequestQueue(this);
    mRequestQueue.add(jsonObjReq);

    It work fine, I wondering what’s wrong with the code?

    Thank you.

    • bradhawk

      Nevermind, I just forget to add the singleton class to AndroidManifest.

      Thanks for the code!

  • kritika

    Hi Ravi, great tutorial.
    I got problem with progress bar.. When app loads data in listview using Volley, progress bar freezes during that time..

  • بافاري ارجنتيني

    executing android update project -p .
    when building a jar file generates this error

    Error: The project either has no target set or the target is invalid.
    Please provide a –target to the ‘android.bat update’ command.

    I searched over stackoverflow and this line works for me

    android update project -p . -s –target android-15

    • Luke

      just download the jar

      • بافاري ارجنتيني

        I know, and I have found and posted the solution, just to help others.

  • Gilbert Sarip

    can’t download source code

  • akhil nair

    hey Ravi while using RestSevices application what request should be used ?

  • Varun Jain

    Hi,
    I tried posting parameters using the code here. On my server end I always receive Null in the request. Some questions on SO suggest that there is an issue with the approach of using getParams(). Any comment on that?

    • Which method you are trying .. POST or GET?

      • Varun Jain

        POST. The getParams() method was never being called. I fixed it by creating a JsonObject and passed it in the JsonObjectRequest instead of the parameter which is null.

        • For POST method it should call getParams(). Anyway you found other way.

          • Android

            I had the same problem and i fixed it by using Json object instead of null, thank you for this great tutorial.

          • rogerio

            How did you do this ?

  • Francisco Magalhães

    Hi Ravi!
    Great tutorial, however, i’m always getting an error saying:
    BasicNetwork.performRequest: Unexpected response code 412 for http://api.androidhive.info/volley/person_array.json

    How can I resolve that issue? I’ve already created another project and the error continues to appear..

    Thanks in advance!

  • Nham Phan Dinh

    Good tutorial.

  • I have a problem in sending the data to server. I use JsonObjectRequest with POST Method. I use getParams() method to send the username and password. But i get null on the server side. Then i use JSONObject at place of null ( 3rd parrameter of JsonObjectRequest) but not get success. Then i used

    $body = file_get_contents(‘php://input’);
    $postvars = json_decode($body, true);

    at server side. Now i get the variable at server side. But Now i get the error at Android Application side.

    I also try to create CustomRequest but not able to get variable at server side.

  • Deep

    It is much better if we use Volley + OkHttp for ultrafast networking for both Image and Http operations.

    Visit : https://gist.github.com/JakeWharton/5616899

  • Dhruvit Darji

    I have created Demo using This tutorial and working fine.. but i would like make 2 call with different URLS
    1) LOGIN
    2) Fetching Data

    So should i have to write following things twice or i can do by writing single time..
    I have done that in Async and its single Async Class.

    I have done following code using volley,

    String urlAuthenticate = “http://qa-xx.xxx.com/web/session/authenticate”;
    String jsonAuth = “{“jsonrpc”:”2.0″,”method”:”call”,”params”:{“db”:”MobileERP_QA”,”login”:”admin”,”password”:”admin”,”base_location”:”http://qa-bma.officebeacon.com”,”session_id”:”263537f931b745a8aa85ee676a4b37dd”,”context”:{}},”id”:”r7″}”;

    String urlSearch = “http://qa-xx.xxx.com/web/dataset/search_read”;
    String jsonSearchContact = “{“jsonrpc”:”2.0″,”method”:”call”,”params”:{“model”:”res.partner”,”fields”:[“sale_order_count”,”title”,”parent_id”,”name”,”street”,”country_id”,”email”,”street2″,”zip”,”country”,”color”,”city”,”opportunity_count”,”phone”,”has_image”,”state_id”,”function”,”is_company”,”meeting_count”,”mobile”,”category_id”,”__last_update”],”domain”:[[“employee”,”=”,false]],”context”:{“lang”:”en_US”,”tz”:”Asia/Kolkata”,”uid”:1},”offset”:0,”limit”:40,”sort”:””,”session_id”:”65f9f11bb977452a8b20b0ab157b7425″},”id”:”r53″}”;

    JSONObject obj = new JSONObject(jsonAuth);
    final ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage(“Loading…”);
    pDialog.show();

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, urlAuthenticate obj, new Response.Listener()
    {
    @Override
    public void onResponse(JSONObject response)
    {
    Log.e(TAG, response.toString());
    pDialog.hide();
    }
    }, new Response.ErrorListener()
    {

    @Override
    public void onErrorResponse(VolleyError error)
    {
    VolleyLog.e(TAG, “Error: ” + error.getMessage());
    pDialog.hide();
    }
    })
    {
    /**
    * Passing some request headers
    * */
    @Override
    public Map getHeaders() throws AuthFailureError
    {
    HashMap headers = new HashMap();
    headers.put(“Content-Type”, “application/json”);
    return headers;
    }
    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

  • vivek

    Hai Ravi,

    I have tried your methods and all getting well. I have some doubt,

    Can we upload and download files from server using volley ? then how ?
    is this the best solution for uploading and downloading files from server ?

    please let me know your suggestion. thnkz

    • Paresh Dudhat

      Hi Vivek i guess you can download / upload files but may be you may not get percentage/status of uploading or downloading

  • Sagar

    Hey Ravi,

    Does this Volley library work for Https requests too? I doubt it because the official documentation says that “Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.”

  • khavq

    Hi Ravi,
    I have downloaded “volley” folder and “Ant apache”.
    then set up JAVA_HOME, ANDROID_HOME, ANT_HOME
    – but when I try update project : android update project -p
    this show : ” sh.exe : android : command not found “

    • after setting the path, did you open new console as the changes won’t effect to current console session.

  • saquib

    Thanks for great tutorials, I am facing empty post param issue from your code, can you help whats going on below code is sending no post params to server

    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;
    }

    };

  • Asad

    Need Help ASAP, I have downloaded your code used it and works fine but when i use your code for downloading image in my app it does not work,here is what i’m using

    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    imageLoader.get(“http://198.199.92.239/CitizensCon//public/images/ImageID130.jpeg”, new ImageListener() {

    @Override

    public void onErrorResponse(VolleyError error) {

    Log.e(“ada”, “Image Load Error: ” + error.getMessage());

    }

    @Override

    public void onResponse(ImageContainer response, boolean arg1) {

    if (response.getBitmap() != null) {

    // load image into imageview

    imageView.setImageBitmap(response.getBitmap());

    }

    }

    });

    I have added AppController class and LruBitmapCache,but the response is null

  • Harun KARACA

    I want to use NetworkImageView in ListView, so there will be more than one link.But, it show just last image.

  • How to parse xml using volley library? Any reference source or example would be great.

  • Guest

    Thanks @ravi8x:disqus, Its works like a charm..

  • The Space Guy

    Great tutorial. Thanks!

  • Harshvardhan Trivedi

    Great!! Thanks man 😀

  • dinesh raturi

    hello ravi,

    i have a query please help !!!!!!!!!!!!!!!!!!

    i want to send text from Edittext to server using volley …..so please send me full source code plzzzzzz…

    Also i want to send image from gallery , to server …… no sourcecode is working for me plzzz helppppp broooooooooo

  • Farzin Hooshmand

    First I wanted to thank you for your great articles. Second, I have a question:

    how can I override caching policy of a server that does not allow caching? is there any way?

  • dinesh raturi

    hey ravi please tell me how to send values to php server using volley …………???

    • Hi Dinesh,

      Please check 6th point in this tutorial. I have posted name, email, password parameters.
      6. Adding post parameters

      • dinesh raturi

        Thankssss man !!! u d best brooooooo ………

  • Vatslav

    Thank you.

  • dinesh raturi

    i got error basicnetwork.performrequest unexpected response code 412 whille sending values to ur given url …………please help bro !!!!! here is my code …..

    package info.androidhive.volleyexamples;

    import java.util.HashMap;

    import java.util.Map;

    import org.json.JSONObject;

    import info.androidhive.volleyexamples.app.AppController;

    import info.androidhive.volleyexamples.volley.utils.Const;

    import android.app.Activity;

    import android.app.ProgressDialog;

    import android.os.Bundle;

    import android.util.Log;

    import android.view.View;

    import android.widget.Button;

    import android.widget.TextView;

    import com.android.volley.Request.Method;

    import com.android.volley.Response;

    import com.android.volley.VolleyError;

    import com.android.volley.VolleyLog;

    import com.android.volley.toolbox.JsonObjectRequest;

    import com.android.volley.toolbox.StringRequest;

    public class StringRequestActivity extends Activity {

    private Button btnStringReq;

    private TextView msgResponse;

    private ProgressDialog pDialog;

    // Tag used to cancel the request

    String tag_json_obj = “json_obj_req”;

    private String TAG = StringRequestActivity.class.getSimpleName();

    String url = “http://api.androidhive.info/volley/person_object.json”;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_string);

    btnStringReq = (Button) findViewById(R.id.btnStringReq);

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

    btnStringReq.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

    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”, “dinesh”);

    params.put(“email”, “leofsdnf@gmail.com”);

    params.put(“password”, “password12354345”);

    return params;

    }

    };

    System.out.print(“”+jsonObjReq + tag_json_obj);

    // Adding request to request queue

    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

    }

    });

    }

    /*private String TAG = StringRequestActivity.class.getSimpleName();

    private Button btnStringReq;

    private TextView msgResponse;

    private ProgressDialog pDialog;

    // This tag will be used to cancel the request

    private String tag_string_req = “string_req”;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_string);

    btnStringReq = (Button) findViewById(R.id.btnStringReq);

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

    pDialog = new ProgressDialog(this);

    pDialog.setMessage(“Loading…”);

    pDialog.setCancelable(false);

    btnStringReq.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

    makeStringReq();

    }

    });

    }

    private void showProgressDialog() {

    if (!pDialog.isShowing())

    pDialog.show();

    }

    private void hideProgressDialog() {

    if (pDialog.isShowing())

    pDialog.hide();

    }

    /**

    * Making json object request

    * */

    /*private void makeStringReq() {

    showProgressDialog();

    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();

    }

    });

    // Adding request to request queue

    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

    }*/

    }

  • Maciej Golianek

    Hey! Is possible to check that image is already downloaded? Is there any method in volley? (Similar to OnPostExecute in asyncTask ?)

  • Edwiin Sandoval

    Great Tutorial budy, thanks a lot !!! Greetings from Durango, Mexico.

  • Aditya Thakar

    Thanks Ravi… U r d best…!!!

  • najoua mahi

    Hi everybody,

    I want to retrieve data using Volley library and i need to send (email & password) in parameters. But the method getParams is not invoking
    Can you help me!

    Thank you.

    • Which method you are using while sending request GET or POST?

      • najoua mahi

        I’m using Post, it works fine when I Override getParams() with StringRequest Object, but it dosn’t work with JSONObjectRequest

        • With JSONObject request you can post params like that. You need to post the params as JSONObject something like {“email”:”youremail”, “password”:”yourpassword”}. Check JSONObjectRequest accepts request json object too.

          • najoua mahi

            Actually i’ve resolved the problem with a custom class:

            public class CustomRequest extends Request{

            private Listener listener;
            private Map params;

            public CustomRequest(String url, Map params,
            Listener reponseListener, ErrorListener errorListener) {
            super(Method.POST, url, errorListener);
            this.listener = reponseListener;
            this.params = params;
            }

            public CustomRequest(int method, String url, Map params,
            Listener reponseListener, ErrorListener errorListener) {
            super(method, url, errorListener);
            this.listener = reponseListener;
            this.params = params;
            }

            protected Map getParams()
            throws com.android.volley.AuthFailureError {
            return params;
            };

            @Override
            protected void deliverResponse(JSONObject response) {
            // TODO Auto-generated method stub
            listener.onResponse(response);
            }

            @Override
            protected Response parseNetworkResponse(NetworkResponse response) {
            try {
            String jsonString = new String(response.data,
            HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
            HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
            } catch (JSONException je) {
            return Response.error(new ParseError(je));
            }
            }

            }

            And then used it like so:

            CustomRequest jsonObjReq = new CustomRequest(Method.POST,
            url,null, new Response.Listener(){

            @Override
            public void onResponse(JSONObject response) {
            Log.d(“response”, response.toString());
            parseJson(response);
            pDialog.hide();
            }
            }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            VolleyLog.d(“Error”, “Error: ” + error.getMessage());
            pDialog.hide();
            }
            }) {

            @Override
            protected Map getParams() {
            Map params = new HashMap();
            params.put(“email”, “user2@gmail.com”);
            params.put(“password”, “user”);

            return params;
            }

            };

            And it works.

  • asif

    Hi,

    while installing apache ant i m getting this msg ‘Buildfile: build.xml does not exist!
    Build failed’ ….plz help

    @Sasndut: Plz share the solution if you know.

  • akhil

    Thanks ravi for the tutorial. am too facing the same problem as that of najuoa mahi. is there any solution for that. if i want to send request in string and get response in json.

  • Mohammadreza Salari

    i have some error when type the “android update project -p .” this —–> ,android, is not recognized as an internal or external command,operable program or batch file. what i doing??? please.

    • Sasndut

      set your JAVA_HOME Environment Variable under Windows to the JDK directory you’ve mentioned do the following:
      1. Click Start, right click on Computer and select properties (you can
      also hold down the windows key and press the pause/break key).
      2.Click on Advanced system settings on the left.
      3.Click the Environment Variables button on the bottom.
      4.Click the New… button below the System variables window.
      5.Enter the following:

      Variable name: JAVA_HOME
      Variable value: C:jdk1.6.0_23

      6. Click Ok, Ok, Ok, and close the system control panel you opened in step 1
      7.Close and re-open your command prompt.

      If you are using Eclipse then skip the steps above and do the following:
      1.Click on the Window menu and choose Preferences.
      2.Expand the Ant entry on the left and click on Runtime
      3.Click on Global Entries in the Classpath tab on the right.
      4.Click Add External JARs…
      5.Navigate to C:jdk1.6.0_23lib and select tools.jar then click open.
      6.Hit ok to Close the preferences Window.

      you can try the steps above, because i also have the same experience,i follow the steps above, and now it is solved 🙂

  • Helevatic

    why not just link us to a copy of volley.jar rather than we all go through git and apache ant to create it

    • Reena Nachare

      Download Sample Code you will get volley.jar

    • It is already there in the tutorial saying “If you are unsuccessful in building the volley, meanwhile you can download volley.jar here”.

      http://api.androidhive.info/volley/volley.jar

    • VladMurray

      I actually didnt mind learning how to build the jar.

  • Mainak

    hi,

    NetworkImageView not working, My code is given below—-

    thumbNail = (NetworkImageView)findViewById(R.id.imageViewSingleEventImage);

    // Parsing json

    for (int i = 0; i < response.length(); i++) {

    try {

    JSONObject obj = response.getJSONObject(i);

    EnentNm = obj.getString("EnentNm");

    EventStartDt = obj.getString("startDT");

    EventEndDt = obj.getString("endDT");

    EventTim = obj.getString("evenTime");

    EventPl = obj.getString("eventPlace");

    EventDesc = obj.getString("eventDesc");

    imagUrl = obj.getString("evenImagePath");

    ImageFinalPath = imagUrl.replace("\", "");

    } catch (JSONException e) {

    e.printStackTrace();

    }

    }

    if(imageLoader == null ){

    imageLoader = AppController.getInstance().getImageLoader();

    }

    tvEventHeading.setText(EnentNm);

    if(EventStartDt.equals(EventEndDt)){

    Newdt =EventStartDt;

    }else{

    Newdt = EventStartDt+" to " +EventEndDt;

    }

    tvEventDate.setText(Newdt);

    tvEventTime.setText(EventTim);

    tvEventPlace.setText(EventPl);

    tvEventDescription.setText(EventDesc);

    Log.d(TAG, ImageFinalPath.toString());

    tvStaticHeading1.setText("Date :");

    tvStaticHeading2.setText("Time :");

    tvStaticHeading3.setText("Place :");

    thumbNail.setImageUrl(ImageFinalPath, imageLoader);//— image is not loading— i get all text data—//[ min api is 8 and max api is 19 ]

    please tell me how to solve this problem ???

  • Rajneesh

    Hey Friends,

    i want to convert “String data = new String(entry.data, “UTF-8″);” To Bitmap please give an idea how to conver if any one knows.

    Thank you.

  • abul

    i use this, but image cann’t show up. (number 8.2)

    “bitmap too large to be upload into a texture”

    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    // If you are using normal ImageView
    imageLoader.get(Const.URL_IMAGE, new ImageListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
    Log.e(TAG, “Image Load Error: ” + error.getMessage());
    }

    @Override
    public void onResponse(ImageContainer response, boolean arg1) {
    if (response.getBitmap() != null) {
    // load image into imageview
    imageView.setImageBitmap(response.getBitmap());
    }
    }
    });

  • abul

    OMG! anyone. please help. how to compress image size using this volley library?

  • mohammed shah

    Hi Ravi,
    How to use Method.POST in JsonArrayRequest ??

  • Mhaesh

    Now i am removed the “GET” and now i am using “POST” in Json Object request ……..But did’t get the result….. any one can help me……

  • prasad Vdv

    I am getting error when android update project -p is executed
    Error: Missing argument for flag -p.

    • newjay

      i think you’ve missed the dot (.) its: android update project -p .

  • Que

    Hello! Thanks for the great tutorial 🙂 I get messed up with a few things so I could really need your help 🙂 The example is working perfect but when I try to build my own once the part isn´t working:

    AppController:
    ….

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

    ERROR: The type DownloadManager.Request is not generic; it cannot be parameterized with arguments

    I have to create it like this:

    public void addToRequestQueue(JsonObjectRequest jsonObjReq,String tag_json_obj)

    {
    getRequestQueue().add(jsonObjReq);
    }

    If you need more details I can mail you the complete source code. Thanks for helping! 🙂

  • Renan Barbosa

    How do I send an image file in a JSON object?

  • Guy Dviri

    All that’s for downloading an image , absolutely nuts.

  • Mahesh Mahi

    I am using below code with “POST” method to receive the data but i am getting “Error message”

    ————********************************************************************************************————

    ——————–@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@————

    String url = “http://api.androidhive.info/volley/person_object.json”;

    showProgressDialog();

    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();

    }

    }) {

    /**

    * Passing some request headers

    * */

    @Override

    public Map getHeaders() throws AuthFailureError {

    HashMap headers = new HashMap();

    headers.put(“Content-Type”, “application/json”);

    headers.put(“apiKey”, “xxxxxxxxxxxxxxx”);

    return headers;

    }

    };

    // Adding request to request queue

    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

  • Alex Mercer Inthi

    How can I load a gif into Volley NetworkImageView?

  • Abhijeet Bhosale

    Hi Ravi,

    Thanks yaar for tutorial, Nicely written.

    I have a query or just need to confirm.

    like in HttpClient- HttpPost

    we can directly send the json request as a string.

    like something;

    httppost.setEntity(new StringEntity(jsonObj.toString()));

    But in volley, we need to send these values through

    getParams() only?

    As i think it will very dirty code, if need to send more request values and what for passing the arraylist?

    let me know your thoughts.

    Thanks Yaar 🙂

    • Abhijeet Bhosale

      @ravi8x:disqus any thoughts?

  • Victor Kurauchi

    Hi Ravi, great article. I’m new with Android and you’re the reference with your posts. One question: Volley should work with AsyncTask like defaultHttpClient ? Thank you.

    • Volley takes care of Aynctask internally. Why are you worring about http clients again?

      • Victor Kurauchi

        Actually, i’m not worrying about it, i’m just trying to find where my error occurs after the request (new with Android). Found that App is crashing in the line AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj) with NullPointerException. Still figuring out

      • Hey Ravi i am not able to send the variable to server using JsonObjectRequest?
        Can you please help me ?
        Its an request

  • Noor

    How to get json array and json object in one call through volley

    • Noor

      Got my answer.. Just use of JsonObjectRequest

      Nice tut ravi
      expecting more in future

    • Hey Noor are you able to send the variable to server using JsonObjectRequest?
      i am suffering from this issue please help.

  • Noor

    6…
    params is not sending check it at php side

    • Code Fan

      Check my post.

  • Trey Rosius

    Hi Ravi!! the 6th method to post params does’nt seem to work.I’m passing pid as the parameter to get single product from database to no avail….any suggestions.Please

    • Code Fan

      Check my post.

      • Trey Rosius

        Thanks Mayne….I got it working with String request

      • Guest

        hey master!
        can you give me solution how to get the image from listview that you clicked and intent the image to another activity?

        • Code Fan

          What I understood from your question (excuse me if I’m wrong), you’ll need to have a custom list view adapter with overriden getView method. Try to use viewholder pattern as well for the performance sake.

  • Code Fan

    At 6th method, JSONObjectRequest sending JsonObject as parameter. If your server side content type is not “application/json”, it won’t be able to get the inputs; thus won’t be able to submit the form. Use StringRequest instead.

    • Hey is your code working to passing the parameters with jsonobjectrequest on server side?

      • googler

        my cde is working if u want any helpp

        • Bilal Khalid

          Hey googler thanks for your reply. I am stuck with this problem from last 3 days.
          can you please send me your code if it is possible for you.
          its an request.
          my email id is bkhalid063@gmail.com

        • Hey googler thanks for your reply. I am stuck with this problem from last 3 days.
          can you please send me your code if it is possible for you.
          its an request.
          my email id is bkhalid063@gmail.com

        • Can you send me your code please at bkhalid063@gmail.com ?

  • Midas

    Quick question, if I don’t manually clear the cache, does it stay around indefinitely?

  • Daniel

    Hi Ravi,

    thank you for your tutorial. I have a problem with JsonObjectRequest. I have created CustomJsonObjectRequest that extends JsonObjectRequest. In this class I’m ovveriding getHeaders method and adding Basic Auth header. It is working for devices with API > 10 but for device with android API 10 I’m getting response code 400 from server. Don’t you know where can be the problem? Thank you.

  • Sandeep Gupta

    Hi Ravi, i am unable to install the ANT, i have following location of installations, JAVA: , GIT : , AND i created a Folder in C Drive for ANT : . Using Command prompt , i can execute the the command git , successfully . My environment variables is , ANT_HOME = , JAVA_HOME = , Path = . That’s all , When I execute the command , it gives in Command Prompt , please help, Thanks.

  • Muhammad Zubair

    Hello Ravi
    i have found an issue in this example of yours
    if the image in the link changes in the server then it does not update the image instead keeps displaying the same image from cache even after trying again and again by pressing the button.

  • Romany Bibawy

    How i upload a bitmap image to server using android volley library

  • Guest

    hi how to convert “String data = new String(entry.data, “UTF-8″);” to Bitmap?

  • pop

    how to send raw json?

    • Vinh Trinh

      use StringRequest

  • Sandeep Gupta

    Hi Ravi, i want to load Image loading like Capcha image, and on button click it should be refresh, I read your tutorial, and implement, but it is not re-loading image. i don’t want to use image cache. What to do ?

  • Dilip Birajadar

    Hi Why we need to clone the volly library please tell me…..

  • David Rocha

    Please, make a example about Synchronous requests using volley FutureRequest, there is nothing about on Google! I’m having some problems and I can’t find a solution …

  • marvin

    hi how to convert “String data = new String(entry.data, “UTF-8″);” to Bitmap?

    i badly needed this data to convert to bitmap.

    • marvin

      i got it
      Bitmap bitmap = BitmapFactory.decodeByteArray(entry.data, 0, entry.data.length);

  • Hossein

    hi, thanks for your amazing tutorial, i’m using this library for getting Arabic json arrays and i changed the charset to utf-8… but i get strange characters, can you help me with it?! should i change the encoding of it or what ?? (it’s emergency)

  • Devang

    when i am loading images from web services (32 images) i am retrieving only first 7 images and that 7 images are repeating and filling 32 rows of List View. Can anyone suggest what i should do?

  • Guest

    01-08 13:30:11.612: D/TextLayoutCache(7057): Using debug level: 0 – Debug Enabled: 0
    01-08 13:30:11.612: W/dalvikvm(7057): threadid=11: thread exiting with uncaught exception (group=0x40c481f8)
    01-08 13:30:11.612: E/AndroidRuntime(7057): FATAL EXCEPTION: AsyncTask #1
    01-08 13:30:11.612: E/AndroidRuntime(7057): java.lang.RuntimeException: An error occured while executing doInBackground()
    01-08 13:30:11.612: E/AndroidRuntime(7057): at android.os.AsyncTask$3.done(AsyncTask.java:278)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.lang.Thread.run(Thread.java:856)
    01-08 13:30:11.612: E/AndroidRuntime(7057): Caused by: java.lang.NullPointerException
    01-08 13:30:11.612: E/AndroidRuntime(7057): at com.example.jsonparsing.ServiceHandler.makeServiceCall(ServiceHandler.java:70)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at com.example.jsonparsing.ServiceHandler.makeServiceCall(ServiceHandler.java:32)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at com.example.jsonparsing.MainActivity$GetContacts.doInBackground(MainActivity.java:95)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at com.example.jsonparsing.MainActivity$GetContacts.doInBackground(MainActivity.java:1)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at android.os.AsyncTask$2.call(AsyncTask.java:264)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    01-08 13:30:11.612: E/AndroidRuntime(7057): … 5 more
    01-08 13:30:19.302: E/WindowManager(7057): Activity com.example.jsonparsing.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41356a30 that was originally added here
    01-08 13:30:19.302: E/WindowManager(7057): android.view.WindowLeaked: Activity com.example.jsonparsing.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41356a30 that was originally added here
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.ViewRootImpl.(ViewRootImpl.java:441)
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:279)
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.Window$LocalWindowManager.addView(Window.java:539)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.Dialog.show(Dialog.java:278)
    01-08 13:30:19.302: E/WindowManager(7057): at com.example.jsonparsing.MainActivity$GetContacts.onPreExecute(MainActivity.java:89)
    01-08 13:30:19.302: E/WindowManager(7057): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
    01-08 13:30:19.302: E/WindowManager(7057): at android.os.AsyncTask.execute(AsyncTask.java:511)
    01-08 13:30:19.302: E/WindowManager(7057): at com.example.jsonparsing.MainActivity.onCreate(MainActivity.java:74)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.Activity.performCreate(Activity.java:4469)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread.access$600(ActivityThread.java:127)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1159)
    01-08 13:30:19.302: E/WindowManager(7057): at android.os.Handler.dispatchMessage(Handler.java:99)
    01-08 13:30:19.302: E/WindowManager(7057): at android.os.Looper.loop(Looper.java:137)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread.main(ActivityThread.java:4507)
    01-08 13:30:19.302: E/WindowManager(7057): at java.lang.reflect.Method.invokeNative(Native Method)
    01-08 13:30:19.302: E/WindowManager(7057): at java.lang.reflect.Method.invoke(Method.java:511)
    01-08 13:30:19.302: E/WindowManager(7057): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
    01-08 13:30:19.302: E/WindowManager(7057): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
    01-08 13:30:19.302: E/WindowManager(7057): at dalvik.system.NativeStart.main(Native Method)
    01-08 13:30:21.782: I/Process(7057): Sending signal. PID: 7057 SIG: 9

  • Sivakumar

    Hi Ravi i got this type of error in my Log Cat….Please help me..

    01-08 13:30:11.612: E/AndroidRuntime(7057): FATAL EXCEPTION: AsyncTask #1
    01-08 13:30:11.612: E/AndroidRuntime(7057): java.lang.RuntimeException: An error occured while executing doInBackground()
    01-08 13:30:11.612: E/AndroidRuntime(7057): at android.os.AsyncTask$3.done(AsyncTask.java:278)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.lang.Thread.run(Thread.java:856)
    01-08 13:30:11.612: E/AndroidRuntime(7057): Caused by: java.lang.NullPointerException
    01-08 13:30:11.612: E/AndroidRuntime(7057): at com.example.jsonparsing.ServiceHandler.makeServiceCall(ServiceHandler.java:70)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at com.example.jsonparsing.ServiceHandler.makeServiceCall(ServiceHandler.java:32)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at com.example.jsonparsing.MainActivity$GetContacts.doInBackground(MainActivity.java:95)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at com.example.jsonparsing.MainActivity$GetContacts.doInBackground(MainActivity.java:1)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at android.os.AsyncTask$2.call(AsyncTask.java:264)
    01-08 13:30:11.612: E/AndroidRuntime(7057): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    01-08 13:30:11.612: E/AndroidRuntime(7057): … 5 more
    01-08 13:30:19.302: E/WindowManager(7057): Activity com.example.jsonparsing.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41356a30 that was originally added here
    01-08 13:30:19.302: E/WindowManager(7057): android.view.WindowLeaked: Activity com.example.jsonparsing.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41356a30 that was originally added here
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.ViewRootImpl.(ViewRootImpl.java:441)
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:279)
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
    01-08 13:30:19.302: E/WindowManager(7057): at android.view.Window$LocalWindowManager.addView(Window.java:539)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.Dialog.show(Dialog.java:278)
    01-08 13:30:19.302: E/WindowManager(7057): at com.example.jsonparsing.MainActivity$GetContacts.onPreExecute(MainActivity.java:89)
    01-08 13:30:19.302: E/WindowManager(7057): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
    01-08 13:30:19.302: E/WindowManager(7057): at android.os.AsyncTask.execute(AsyncTask.java:511)
    01-08 13:30:19.302: E/WindowManager(7057): at com.example.jsonparsing.MainActivity.onCreate(MainActivity.java:74)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.Activity.performCreate(Activity.java:4469)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread.access$600(ActivityThread.java:127)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1159)
    01-08 13:30:19.302: E/WindowManager(7057): at android.os.Handler.dispatchMessage(Handler.java:99)
    01-08 13:30:19.302: E/WindowManager(7057): at android.os.Looper.loop(Looper.java:137)
    01-08 13:30:19.302: E/WindowManager(7057): at android.app.ActivityThread.main(ActivityThread.java:4507)
    01-08 13:30:19.302: E/WindowManager(7057): at java.lang.reflect.Method.invokeNative(Native Method)
    01-08 13:30:19.302: E/WindowManager(7057): at java.lang.reflect.Method.invoke(Method.java:511)
    01-08 13:30:19.302: E/WindowManager(7057): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
    01-08 13:30:19.302: E/WindowManager(7057): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
    01-08 13:30:19.302: E/WindowManager(7057): at dalvik.system.NativeStart.main(Native Method)
    01-08 13:30:21.782: I/Process(7057): Sending signal. PID: 7057 SIG: 9

  • Brachialste

    Have you worked with XML requests yet? I have my custom wrapper already but i think i’m missing something.

  • Abhishree Comp’s

    Hi Ravi

    I am trying to get data from Cache when internet connection is not available but i could not get it

    I am following previous point is there any other procedure to get data from cache??

    http://www.hdblog.it/api/mobile/getnewslist/?queryfilter=blog130

    • opetmar

      you could do this to get Cached data :

      url = “http://www.hdblog.it/api/mobile/getnewslist/?queryfilter=blog130”;

      Cache cache = AppController.getInstance().getRequestQueue().getCache();
      Cache.Entry entry = cache.get(url);

      if (entry != null) {

      try {

      String data = new String(entry.data, “UTF-8”);

      try {

      JSONArray response = new JSONArray(data);

      for (int i = 0; i < response.length(); i++) {

      try {

      JSONObject obj = response.getJSONObject(i);

      response_status= obj.getString("response_status");
      msg= obj.getString("msg");
      …..
      etc

      } catch (JSONException e) {

      e.printStackTrace();

      }

      }

      } catch (JSONException e) {

      e.printStackTrace();

      }

      } catch (UnsupportedEncodingException e) {

      e.printStackTrace();

      }

      }else {

      // make volley request here

      }

  • abin antony

    its a very good tutorial anyways can we load images to a custom Imageview using this volley library

  • NirM

    Hi,

    Thank’s for this tutorial, I followed your instructions and when I pasted the command “android update project -p .”

    I’m getting a Error msg “Error: C:gitvolley is not a valid project .”
    Any ideas why it might happen?

    Thank’s

  • opetmar

    inside AppController.java you have to change this line inside getImageLoader() from :

    getRequestQueue();

    To

    mRequestQueue = getRequestQueue();

    without this modefication , the image offline cache will not work.

  • AdiB NoH

    why we need to include android:name=”info.androidhive.customlistviewvolley.app.AppController” in android manifest?

    • Marina

      Because you provided your own implementation of Application.

      Application:
      “Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml’s tag, which will cause that class to be instantiated for you when the process for your application/package is created.”
      http://developer.android.com/reference/android/app/Application.html

      However, it also says that subclassing Application is discouraged.

      “There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally usesContext.getApplicationContext() when first constructing the singleton.”

      http://developer.android.com/reference/android/app/Application.html

      And here’s how to set up static Singleton class.

      http://developer.android.com/training/volley/requestqueue.html#singleton

  • Atula

    I download your source and change Const.URL_IMAGE by with :
    http://4.bp.blogspot.com/-cCN6UeXq8Jo/U9pDBzIsU4I/AAAAAAAAq74/4OYFZTKLDGM/s0/3.jpg
    and re-run but cannot display image, i don’t know why, please help me

  • AaA

    Hi,
    how can use my web-service? i don’t like picasa 😐

  • Ali Arasteh

    Hello Ravi.
    Thank you for your great article as always.
    Now I’m using volley as the main source for my networking actions. just need a little help with caching images; does volley store data on memory? and if it does, how could I cache my data on disk instead of memory? actually I’m losing images when user clears memory and I don’t want it to happen.

    by the way how can I contact you (I’m starting something and need to talk and need some help).

  • Hiếu Giề

    Hello Ravi.

    how can i put param in to json array request like json object request ?

  • Hi Ravi, thanx a lot for your work.
    Is it possible to download binary files, possibly with progress?

  • Guest

    Hi,
    I use volley but still don’t get any response
    i have url http://rajaongkir.com/api/cost?key=427a68b6c5747f2e7ff1871e80ee7f86&destination=89&weight=1000&origin=176

    to get the response must use POST method
    – url request http://rajaongkir.com/api/cost
    – content-type application/x-www-form-urlencoded
    – and parameter content to send key=427a68b6c5747f2e7ff1871e80ee7f86&destination=89&weight=1000&origin=176

    what must i do?

  • Guest

    Hi,
    How to use Method POST with content string parameters body with volley?
    Sorry i am really newbie

  • Nikunj

    hi ravi, great work, but i just got an issue with the cross language implementation. can you help me out with it?

  • Łukasz Żymła

    Hello Ravi,
    is there any options to get dependencies link, to use volley with Android Studio and gradle?

    • James Seddon

      Add this to the gradle file

      compile ‘com.mcxiaoke.volley:library:1.0.+’

  • Harish

    Hi Ravi,
    First of all thanks for such a nice tutorial on using volley lib.
    One thing I would like to know is how can I use this lib to make Https requests.
    thanks in advance!

  • mohamed

    how i can use volley to load data from mysql data base (image ,text……) ??

  • sheik

    how to download pdf,docx files from json say

  • sheik

    some of the different formates of files from json how can i download that different formates of files (pdf,docx etc….)when button click can you give link or code to learn and implement in my project hurry…….

  • Ragim

    The worst SHIT i ever seen! Why i can’t set TIMEOUT??? Why i can’t get STATUS CODE?

    • Ragim

      I Spend whole day to implement this shit! and this Library is too bad that user can’t get simple things from response like status code!

      • Reza

        You can set TimeOut by overriding getRetryPolicy() and returning custom retry policy and you can get status code by overriding parseNetworkResponse(NetworkResponse response) easily

        response.statusCode