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 = "https://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 = "https://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 = "https://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 = "https://api.androidhive.info/volley/person_object.json";
		
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();		
		
		JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
				url, null,
				new Response.Listener<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 = "https://api.androidhive.info/volley/person_object.json";
		
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();		
		
		JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
				url, null,
				new Response.Listener<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)
Subscribe
Notify of
guest
423 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Raj Amal
6 years ago

Nice article..

oplog
oplog
6 years ago

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
Ngô Văn Bằng
6 years ago
Reply to  oplog

it mean many request ? .

Ravi Tamada
6 years ago
Reply to  oplog

Why do you want a prolong request?

Can
Can
6 years ago

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

Tarik Laila
Tarik Laila
6 years ago

thanks

Nitin Misra
Nitin Misra
6 years ago

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

Trần Minh Thuận
Trần Minh Thuận
6 years ago

Very nice. Thanks

yeah1boy
yeah1boy
6 years ago

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

Satyaki Mukherjee
Satyaki Mukherjee
6 years ago

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 .

Ravi Tamada
6 years ago

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

forall02
forall02
6 years ago

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

forall02
forall02
6 years ago
Reply to  forall02

please help me

Ravi Tamada
6 years ago
Reply to  forall02

Keep android-sdk-windowstools in your Environmental variables.

EnvyAndroid
EnvyAndroid
6 years ago

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

Ravi Tamada
6 years ago
Reply to  EnvyAndroid

Yes

akhil nair
akhil nair
6 years ago

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

Ravi Tamada
6 years ago
Reply to  akhil nair

Read 6th and 7th points.

kady
kady
6 years ago

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
MRX
6 years ago

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
Louis
6 years ago

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
Guest
6 years ago

Gooooooooob tutotial Ravi 😀

VLEIX
VLEIX
6 years ago

Goooooooood tutotial Ravi 😀

Ravi Tamada
6 years ago
Reply to  VLEIX

Thanks VLEIX.

Felix Andego
6 years ago

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
Can
6 years ago

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
Naik
6 years ago

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
Guest
6 years ago

How to set session cookies using Volley Library

Guest
Guest
6 years ago

Great tutorial!!works like charm!!

Vineel Sadineni
Vineel Sadineni
6 years ago

Great tutorial!! works like a charm!!

diegoPy
diegoPy
6 years ago

Great one Androidhive!

Guest
Guest
6 years ago

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
Edwiin Sandoval
6 years ago
Reply to  Guest

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

Siddiq
Siddiq
6 years ago

Is there any other networking library other than Volley.

Ravi
Ravi
6 years ago

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

bradhawk
bradhawk
6 years ago
Reply to  Ravi

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
bradhawk
6 years ago
Reply to  Ravi

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
bradhawk
6 years ago

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
bradhawk
6 years ago
Reply to  bradhawk

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

Thanks for the code!

kritika
kritika
6 years ago

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

بافاري ارجنتيني
بافاري ارجنتيني
6 years ago

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
Luke
6 years ago

just download the jar

بافاري ارجنتيني
بافاري ارجنتيني
6 years ago
Reply to  Luke

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

Gilbert Sarip
Gilbert Sarip
6 years ago

can’t download source code

akhil nair
akhil nair
6 years ago

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

Ravi Tamada
6 years ago
Reply to  akhil nair

I suggest you use json.

Varun Jain
Varun Jain
6 years ago

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?

Ravi Tamada
6 years ago
Reply to  Varun Jain

Which method you are trying .. POST or GET?

Varun Jain
Varun Jain
6 years ago
Reply to  Ravi Tamada

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.

Ravi Tamada
6 years ago
Reply to  Varun Jain

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

Android
Android
6 years ago
Reply to  Ravi Tamada

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

rogerio
rogerio
6 years ago
Reply to  Android

How did you do this ?

Francisco Magalhães
Francisco Magalhães
6 years ago

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
Nham Phan Dinh
6 years ago

Good tutorial.

Joginder Sharma
6 years ago

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
Deep
6 years ago

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
Dhruvit Darji
6 years ago

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
vivek
6 years ago

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
Paresh Dudhat
6 years ago
Reply to  vivek

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

Sagar
Sagar
6 years ago

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
khavq
6 years ago

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 “

Ravi Tamada
6 years ago
Reply to  khavq

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

saquib
saquib
6 years ago

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.info”);
params.put(“password”, “password123”);

return params;
}

};

Asad
Asad
6 years ago

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
Harun KARACA
6 years ago

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

Siddharth Vyas
6 years ago

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

Ravi Tamada
6 years ago
Reply to  Siddharth Vyas
Siddharth Vyas
6 years ago
Reply to  Ravi Tamada

Thanks a lot :disqus Its works like a charm..

Guest
Guest
6 years ago

Thanks :disqus, Its works like a charm..

The Space Guy
The Space Guy
6 years ago

Great tutorial. Thanks!

Harshvardhan Trivedi
Harshvardhan Trivedi
6 years ago

Great!! Thanks man 😀

dinesh raturi
dinesh raturi
6 years ago

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
Farzin Hooshmand
6 years ago

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?

Ravi Tamada
6 years ago

I haven’t tried. But below link may helps you. Check second answer where he is saying override parseCacheHeaders() method.

http://stackoverflow.com/questions/16783177/set-expiration-policy-for-cache-using-googles-volley

dinesh raturi
dinesh raturi
6 years ago

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

Ravi Tamada
6 years ago
Reply to  dinesh raturi

Hi Dinesh,

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

dinesh raturi
dinesh raturi
6 years ago
Reply to  Ravi Tamada

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

423
0
Would love your thoughts, please comment.x
()
x