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

      • Yes ,as per Android Documentation, the approach to subclass Application and set up the RequestQueue in Application.onCreate() is discouraged; a static singleton can provide the same functionality in a more modular way.

  • 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

  • hari

    how do i post the image to my server.

  • hari

    how do i post an image to my server using multipart-form-data

  • AdiB NoH

    03-26 11:42:13.369 13318-13348/com.adibnoh.aes D/Volley﹕ [1126] BasicNetwork.logSlowRequests: HTTP response for request= [lifetime=6952], [size=8276], [rc=200], [retryCount=1]

    I got this error, can anyone here help me fix this problem.

    tq in advance

  • stalin

    computer name “hitler” great job Ravi

  • nivas

    what about put bro.

  • nivas

    What about METHOD.PUT bro.

  • farhad

    Hi, Ravi
    I need clear cache of image by url or invalidate it in android volley such as json or string request in queue.
    If guide me, I would be grateful.
    Thanks Ravi

  • hevilp

    Ill get : “TAG cannot be resolved to a variable” , how to fix?

    • hevilp

      found it…

      • helpew

        Please share.

  • Abdou Kabore

    Good tuto Ravi. Please i need to know how if it’s possible to cache on disk with volley. Is it recommended?

  • please help me it is showing unknown host exception http://api.androidhive.info/volley/person_object.json

  • mike

    it does not send POST parameters =(

    • mike

      and AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); return Error Caused by: java.lang.NullPointerException

      • mike

        found it! use StringRequest instead of JsonObjectRequest… looks like this is old tutorial, and some moments where changed by Google.developers.

  • help not posting here

  • franklin joney

    Hi,

    please anyone help me with soap in android

  • Esref

    It’s not posting (putting) json on json file on url.How i write (send) something? I made a movie comment application and the last thins is the sending a comment.But put params code not working.

  • Gilles

    Hi, when i use the above code to sent data to my jboss server i recieve null everywhere is there any trick someone can give me?

  • Atul Yadav

    Hi Ravi,
    how can I manage Volley-request on Orientation change, can you please help me.

    • oscar

      manage network request on activity or fragment lifecycle not is appropriate, you must do this in a service!!

      • Atul Yadav

        @disqus_WaWqruNoO6:disqus I want to show loading Dialog in between request sent & get response, How I can achieve this while using service. please clear.

        • oscar

          the easiest way to do that is doing all the work in an internet service and deliver results through broadcast. looking intent and BroadcastReceiver service.

  • yuanchieh

    Hi, thanks for the useful tutorial~
    I got a question, volley would handle the cache by default, why should we implement by ourselves?
    If I wana load image from cache, how should I do(I use Networkimage)?
    Thanks

  • Naveen Mishra

    Hi Ravi, As per Google Volley is fast way to get connect with web-services,
    what about Retrofit is it really 70% fast than Volley.

  • ensr

    hi, I create an object req. But ı have noting onResponse or onError methods. Please help

  • Sandeep Gahlawat

    In order to create volley.jar when i type “android update -p . ” command it says ‘android is not as internal or external command, operable program or batch file.’
    now, what should i do to resolve this ?

    • You need to add the android sdk to Environment Variables.

  • Sandeep Gahlawat

    i have one final question, can google volley be used to connect android app with AWS EC2 server?
    If yes can u post a small tutorial or something.
    TIA

  • sanket pahuja

    Hi
    I created my application using the code given here and it is successful in fetching the JSONObject from the above mentioned URL’s. However, all I get is a blank screen while trying to fetch this from another URL:

    {“book_id”:540256,”isbn”:”0439332931,9780439332934″,”title”:”The Lucky Lottery”,”author_name”:”Ron Roy”,”page_count”:”86″,”published_year”:”2000″,”popularity”:139306,”label”:[“Book”,”ActiveBook”,”Contemporary”]}

    Please help me here and notify me about the rectifications required so that I am successfully able to implement this.

    • Angel

      do you have the url ?, are you parsing the elements to json ?

      • Angel

        from json*

  • Hari Enaganti

    Hai,I want to know How much data is sending/Receiving speed while android Mobile Data is enabled?
    Any answers appreciable,Thankq guys in advance.

  • Bissenbay Dauletbayev

    Hello! In getParams() method how to different type of data. For example i want to send float, string and int data types to the server. How to send different data types using Volley Library. Thank you!

  • Sakthivel A

    Hi, I need to download more then one video from server. Which one is better volley or Http or any other way? I am new with this one. Please give yours suggestion. Thanks in Advance.

  • Revanth Krishna Kumar

    Getting this Error:

    08-26 20:42:30.429 13374-13394/? E/Volley﹕ [1365] NetworkDispatcher.run: Unhandled exception java.lang.RuntimeException: Bad URL null

  • Trey Rosius

    perfect article!

  • James Tan

    using ant to compile is outdated, its currently being handled in gradle.
    my gradle path is in:
    /Applications/Android Studio.app/Contents/gradle/gradle-2.4/bin/gradle

    and android path is not at
    path-to-android-sdk/tools/

  • James Tan

    Latest volley is available in maven repository,
    therefore, you do not need to compile volley from source code.
    goto Build > Library and dependencies > dependencies
    click + add, search for volley
    com.mcxiaoke.volley:library:1.0.18

  • sushma

    RegisterActivity﹕ Registration Error: null, i am getting this error .. how to solve this

  • sushma

    this error{“error”:true,”error_msg”:”Required parameter ‘tag’ is missing!”}. if i click or register i am getting

    E/RegisterActivity﹕ Registration Error: null

    D/Volley﹕ [1] Request.finish: 7837 ms: [ ] http://192.168.0.7/android_login_api/ 0x355f55a NORMAL 1

    why this error ? and how to solve this?

    • You need to send a parameter named ‘tag’ along with other parameters.

      • Nikhil Nangia

        please ellaborate ravi need it urgently

        Rhanx in advnc

    • Gautam

      Could you please explain again what your error is? Please go through my comment as well, is it the same thing that you are experiencing?

  • Hanan

    how to retrieve data from mysql database using android volley library??plz help:thanx in advance

  • Howard

    great tutorial! keeps working!

  • Kavya

    A very good tutorial!
    I believe you have been using volley for some time,would you prefer to use volley or move to use OkHttp or other lib?Pls mention your suggestion,that would be great

  • Gautam

    I have used Volley as described in your Android Login and Registration Application. However, error occurs when I try to register and nothing is saved in database. Since the toast depicting the error is blank, it is difficult to figure out what is the error. What are the possibilities?

    P.S. I am talking about this method

    new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    Log.e(TAG, “Registration Error: ” + error.getMessage());
    Toast.makeText(getApplicationContext(),
    error.getMessage()+” VOLLEY ERROR”, Toast.LENGTH_LONG).show();
    hideDialog();

    When I click on register, a toast appears saying “null VOLLEY ERROR”. Where am I going wrong?

  • Carlos Suazo

    HI
    How can I disable asyncronous request? using volley

  • bipul prasai

    .loginandregistration D/RegisterActivity﹕ Register Response: {“error”:true,”error_msg”:”Required parameter ‘tag’ is missing!”} how to solve these please help me

  • Kunal

    How to send data from activity to client server using this library

  • HK

    Hi.
    Great tutorial. I have used Volley and found it great.
    But recently, for one of the app I was trying to use Volley for HTTPS web services and found it not working properly.
    Can you give some idea whether Volley supports HTTPS and if yes are there any special pointers that I should keep in mind so as to achieve that.

  • Muh Irzaq
  • vikas kumar

    can you find out what i am doing wrong …here is my code and i am making a jsonobject request and want to receive the jsonobjects from php mysql server,
    JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, url, null,
    new Response.Listener()
    {
    public void onResponse(JSONObject response) {
    Log.d(TAG, response.toString());
    hidePDialog();

    // Parsing json
    try{
    JSONArray ja = response.getJSONArray(“results”);
    for (int i = 0; i < ja.length(); i++) {

    JSONObject obj = ja.getJSONObject(i);
    UserData data = new UserData();
    data.setName(obj.getString("name"));
    data.setBloodGroup("Blood Group : " + obj.getString("bloodgroup"));
    data.setCity(obj.getString("city"));
    data.setPhone(obj.getInt("phone"));

    // adding movie to movies array
    dataList.add(data);

    }

    }catch (JSONException e) {
    e.printStackTrace();
    }

    // notifying list adapter about data changes
    // so that it renders the list view with updated data
    adapter.notifyDataSetChanged();
    }
    }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    VolleyLog.d(TAG, "Error: " + error.getMessage());
    Toast.makeText(getApplicationContext(), error.getMessage()+" "+query, Toast.LENGTH_LONG).show();
    hidePDialog();

    }
    }){
    @Override
    protected Map getParams() {
    Map params = new HashMap();
    params.put(“city”, query);
    return params;
    }
    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjectRequest);
    }

    }
    }

  • kaziolas

    To be honest, this tut suck so bad. It says for beginers..

    Where the hell you put Making json object request??? Or any of that code..Naming of the project and other stuff is just too complicated for beginners.. Really bad tutorial.. Next time create a video instead of this text where everyone can fallow properly..

  • bharath sk

    How to store original images in server using volley?

  • rohit

    Anybody tell me how to get data in android listview using localhost sever in android

  • Virender

    Great Tutorial.

    I am implementing the same but with the .Net Web Service (.asmx). Its a Http POST Web Service. Everything is working fine and WebService returning JSON object, which i can parse successfully.

    But when i trying to POST some data to the service, its returning volleyError (ServerError). No further messages, nothing.

    I try sending HashMap as well as JSON Object, but still its not working. Try to change headers content-type. But still no luck.

    Can you please help, how this works. And what would be the parsing of input stream to get Posted data on the Server side.

    Below is the code of CustomJSONObject Request.

    //////////////////////////

    JSONObject params = new JSONObject();
    try{
    params.put(“lat”, this.currentLocation.latitude);
    params.put(“lng”, this.currentLocation.longitude);
    params.put(“rad”, this.currentRadius);
    }
    catch (JSONException j) {
    j.printStackTrace();
    }

    CustomJSONObjectRequest request = new CustomJSONObjectRequest(Request.Method.POST,
    WebService.getAbsoluteURL(WebService.GetMonumentListByRange), params, new Response.Listener() {
    @Override
    public void onResponse(JSONObject response) {
    //Log.i(TAG, “Monument List Loaded.” + response);
    try {
    JSONArray array = response.getJSONArray(“data”);
    DataList list = DataList.getInstance();
    for(int i=0; i<array.length();i++){
    JSONObject obj = array.getJSONObject(i);
    RegionVO vo = new RegionVO(obj);
    list.add(vo);
    }

    Log.i(TAG, "Monument List Parsed. Size:" + list.size());
    }catch (JSONException je) {
    je.printStackTrace();
    }

    showMonumentsInRange();
    }
    });

    CustomRequestQueue.getInstance().getRequestQueue().add(request);

  • VISHWANATH R

    I am getting this error.
    Error:(24, 13) Failed to resolve: com.mcxiaoke.volley:library-aar:1.0.0
    can anyone help me to fix this..

  • kelomaniack

    Great tutorial !!! Congrats! You are the best

  • jhansi laxmi

    Hi Ravi,
    why i am unable to subscribe and download your code? i am not getting any confirmation mail after subscribe.

  • jhansi laxmi

    hi ravi,

    Adding post parameters example you are using the url: http://api.androidhive.info/volley/person_object.json

    But in hashmap you are adding “password” in that url password parameter is not their.
    please can you proved proper url? (if possible one example)
    thanq

  • umer

    hello guys can some one tell me whether we can download files using volley or not and if we can please post the link

  • Ankit Bhalla

    I am getting an error “Unexpected response code 500 for <>”

    this is when i am trying to get the service hit from my url.

    • Aya. M. Salama

      the error is in the service you’re retrieving itself, test your back end links first

  • Raymond Jonathan Tan

    Hi Ravi! maybe you can explain the difference JsonObjectRequest and StringRequest
    I tried to find it on google, but couldnt find it. Which one is better? Maybe androidhive can be the first who explain it!

  • dbnex B

    this post sucks, very poor explanation (or rather no explanation at all), code download not working, signing up not working, poor examples…

  • Anil

    Hi Ravi,
    Your tutorials very good and informative, please make some tutorial on retrofit

  • shima

    hi
    i can not download code
    i registered for Subscribe but i didnt resive verify email
    please help

    thanks

  • Pranav Sharma

    I used this example to understand Volley, it did work in my project but the data downloaded always reloads whenever i switch between fragments in my activity (I was using volley to download data nad display it on one particular fragment) Any idea how to prevent this reload ?

    • It’s not the problem with volley. Normally fragments will be recreated on resume.

      In order to stop volley downloading the data again and again, you need to set the expiry date for that particular resource on server. Then volley will cache the data.

    • Its not the problem of volley. Normally fragments reloads when you switch them. One way is to store the result in SQLite and check before downloading again.

      In order to volley to stop downloading resources again and again, you need to add expiry header on the server to the resources.

  • yeshaya palepogu

    I have an error of (addTorequestQueue) please help me…..

    AppController.getInstance().addToRequestQueue(regReq);

  • yeshaya palepogu

    when I am working with Volley the error raised

  • Nilesh Panchal

    How to use json with soap
    Please help me

  • Loganat

    Very much informative… Thanks for the info 🙂

  • Apurv Thakkar

    Thanks Ravi for this tutorial..I want to ask that json request is made on static url and no parameters are passed to that url..so what to do if i want to pass some parameters to url??

    • Use StringRequest which accepts plain key value params and parse the json manually in onResponse method.

      • Prachie Gupta

        parameters are even null when i am using it with String Request .Please help ravi !!

  • yeshaya palepogu

    AppController.getInstance().addToRequestQueue(volleyRequest);
    When I am working with volley errors are raised please help me Ravi.

  • Mainak

    How Do I Play Video in ListView like Instagram. please say some thing about this.

  • Geraldo K Fillipus

    Nice tutorial Bro. But I am getting “Unfortunatly your app has stoped working”, after i open the activity that is holding the list ! is the anything i might have missed out? i followed the tutorial more than 5 months now

    • Check the LogCat for errors.

      • Geraldo K Fillipus

        Hi rav
        I’m getting something saying failed to connect to Android client connection refused

        • Ankit TheLearner

          “Connection Refused” happens when you don’t have authorized access to the website. If you are using WiFi, check if you’ve logged in properly. Afterwards, ensure that the API key you’re using is correct. I had my issue resolved by this.

      • Geraldo K Fillipus

        Hi Ravi, i am having a different list of activities with different info, so how do declare the app when the the list will not be tdisplayed on the main activity?

      • Geraldo K Fillipus

        Ravi, its working now perfect after i removed this code // changing action bar color

        getActionBar().setBackgroundDrawable(

        new ColorDrawable(Color.parseColor(“#1b1b1b”)));

        now the problem is my activity doesnt have a title, so what do i do

      • Geraldo K Fillipus

        Also i use your other tutorial integration with Paypal, now i am getting unfortunately your app has stooped working, could this be that the app is fighting with the other activity that are using the app in the app the directory?

  • Mohamed Lacarne

    Hello mister Ravi Tamada , thank you for your tutorials they are helping
    me a lot . I have A question : how can i use the post parameters using
    JSonArrayrequest..i’ve been searching throught the internet but didn’t
    find anything useful .

    • You can’t post params using JsonArray or JsonObject request. They accepts json objects as params not plain params. For this you need to use StringRequest and pass the parameters.

      • Mohamed Lacarne

        okay i’m gonna try it , thank you 🙂

      • Mohamed Lacarne

        tried it and worked perfectly ! thank you mister Ravi Tamada you just saved my life 😀

  • Samson Deonyx

    Hello Ravi, I’m working with a video app and i want to load both video and images with volley and i’m wondering how i can get it done

    • For videos you don’t need volley library. MediaPleyer can play video from url.

  • Nishu

    Good tutorial Ravi, can you give me some sample IMAGE URL which i can post in method, for a working example

  • @rpit Patel

    Good explanation ravi sir

  • Eldhose

    BasicNetwork.performRequest: Unexpected response code 412 for http://api.androidhive.info/volley/person_object.json

    03-17 17:12:18.020 3906-3906/codmob.com.volleytest D/Volley: [1] 2.onErrorResponse: MainActivity

  • Dattatreya Kulkarni

    How to get paramater in web app? means in servlet dopost method using request.getparameter(“name”), If i use StringObject Request I will get.. I am not getting for Json Object Request

    • JsonObject request won’t accept plain params. It accepts only JsonObject as param (not sure whether in params or in request body). You need to modify your servlet code to accept jsonobject request.

      • Dattatreya Kulkarni

        ok sir tyu:)

        • Prachie Gupta

          Did you get how to post params using volley? Please help

          • shashi patil

            yes

  • David Pichard

    What about using Volley to hit google cloud endpoints and specifying a google credential for the call? Any tips on this use case for volley?

  • Venktesh Sakthi

    Adding parameters using JSONObjectRequest is wrong…check it…
    http://afzaln.com/volley/com/android/volley/toolbox/JsonObjectRequest.html
    you should not specify null there in constructor.

  • Nishu sharma

    Hello Ravi bhai,
    first of all thanks,
    i follow your tutorials and learned alot,

    i used your code in live project in my company, i post email and password to server by overriding getParams() method but the values are not actually post at server,

    i searched about it and i found this

    http://stackoverflow.com/questions/19837820/volley-jsonobjectrequest-post-request-not-working?rq=1

    there are more developers having same issue ,
    they found solution by creating a Custom JsonObjectRequest class,

    so i want to confirm that does your code (by overriding getParams() method) can post values to server or i have to create Custom JsonObjectRequest class??

  • Dnyanesh Kalal

    hii Ravi sir ..
    i just want to know how to fetch data from sql server from multiple tables into sqlite tables??
    plz give rply quickly sir plz…

  • development techlab

    How can i get the Title of the Image(if there) and shown in the next activity:

  • net kom

    04-09 13:31:52.795 11390-11390/com.example.adi.mysqlandroid D/Volley: [1] 4.onErrorResponse: MainActivity

    04-09 13:31:52.992 11390-11455/com.example.adi.mysqlandroid V/RenderScript: Application requested CPU execution

    04-09 13:31:52.996 11390-11455/com.example.adi.mysqlandroid V/RenderScript: 0x5593cec2f0 Launching thread(s), CPUs 4

    04-09 13:31:56.793 11390-11390/com.example.adi.mysqlandroid D/MainActivity: [{“name”:”thomas”,”username”:”thomas123″,”password”:”password”},{“name”:”jebo”,”username”:”jebo”,”password”:”jebo123″},{“name”:”joko”,”username”:”joko”,”password”:”joko123″},{“name”:””,”username”:””,”password”:””}]

    04-09 13:32:02.105 11390-11390/com.example.adi.mysqlandroid D/Volley: [1] 4.onErrorResponse: MainActivity

  • net kom

    can help my error
    i use volley for get data for json object

  • net kom

    and have example create json with php

  • Danilo

    Hello Ravi Tamada, congratulations for this post and your website where I always find post extremely interesting and clear.

    I am currently investigating the use of the library Volley and I wondered how it was possible to use it to implement a secure connection. The ideal would be if you could publish a professional article on this topic. On the web I found many custom solutions consisting in accepting any certificate but nothing concrete that can act a bit as reliable guideline.

    Greetings,

    Danilo.

    • ARASHI Funsho

      yo Bro!.. How did you resolve the https connection requests?

  • agman rangi

    i want to use the android service concept to get the json request using volley, please help me in doing so.

  • Ravindra(Ravi) verma

    Need to call mRequestQueue.start(); in getRequestQueue Method otherwise code won’t process any request.

    Correct me if i am wrong any where ?

  • SID

    Ravi you need to update your dependency line. com.mcxiaoke.volley:library-aar:1.0.0 this is become deprecated. Use this line instead official by google. compile ‘com.android.volley:volley:1.0.0’

  • reiroku

    How to make new TextView in Response Listener? if i put TextView tv = new TextView(this); in Response.Listener it will show text view cannot be applied to Response Listener

  • Sơn Trần Tuấn

    Hi Ravi Tamada!
    I’m using volley library to upload file, but when i upload a large file (>150MB), i have issue out of memory.
    Can you a solution to solve it.
    Thanks!

    • Don’t use volley to upload files. It is not supported for larger files.

  • Ratnesh Komplli

    Hi Ravi,

    I’m using volley library in app but when using 3G network or 2G network its getting volley Error i.e. Response Code 200 or BasicNetwork.performRequest: Unexpected response code 502

    Please help me on this
    Thanks!

  • Abhishek Saxena

    hey buddy how to post parameter to webservice….i used stringrequest but its not working??

  • Martin Musale

    Hi Ravi, how would you post to HTTPS? Been getting SSL error and material online seem not to fix it.

    • ARASHI Funsho

      How do we post to https? were you able to find a solution/hack?

  • Suzan Mak A

    love this tutorial

  • Prashanth Debbadwar

    Hi Ravi,
    I have Profile pic upload feature. I am using NetworkImageview to load profile pic. In server profile pic changes but not url. Because of url not changing I am getting old image until I kill the app and open. So I tried getCache().invalidate and getCache().remove but both are not working. I tried evening creating new instance of ImageLoader and request que. Any of the technique not working. any idea?

  • Celso Júnior

    The “clear” method on the item 7.5 “Deleting all the cache” don’t takes an url parameter

    • clear() method is used to clear cache for all the urls, if you want to clear specific url use remove(url) method.

    • ramesh chandran

      True. I think its a mistake. The working code is given below.
      AppController.getInstance( ).getRequestQueue( ).getCache( ).clear( );

  • nice one …

  • Bhavna

    Awesome..With your tutorials there is no need to go and search anything on web.

  • Tony

    Nice tutorial.
    But I am not able to clear Volley cache using none of the above mentioned methods. Please help

  • Enthralltech

    I want to hit a url with post parameter and post data can be jsonObject or jsonArray, how do i do that? please help.

  • Munna Shaik

    Hi Ravi, I want to send the token in every request in android volley. Is there any interceptor in android volley we can send the headers in each request without adding in every rqst like headers.put(“auth-token”,””);

  • Fabio

    Has anyone had problems with Volley double post; It runs twice and should run only one. Help Me !

    • shashi patil

      try adding this
      RetryPolicy retryPolicy=new DefaultRetryPolicy(0,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DEFAULT_BACKOFF_MULT);
      stringRequest.setRetryPolicy(retryPolicy);

  • pepe

    Could you give and example of using GsonRequest with custom objects to manage POST request and the response from the RestAPI?

  • ar ta

    hi ravi
    I use Volley library in my app and everything is ok but when I send a request I can see the following in androdi studio log cat

    Full Url of my server
    Name of parameters
    and other values.
    I also check it with Ettercap tools in Kali linux and it’s show me the same. My question is now is how can hide this from users?

  • Harsh Tanwar

    hello sir,
    i use volley library in my app,everything is worked fine but my senior says that we should use a volley library using bean class ( getter and setter methods) and GSON library for JSON parsing. but i want JSON parsing in a single class like as your example. so i am totally confused that which way is better for me.
    So please help me.

  • sona

    how to send video as file in volley library android?

  • Aby Zou

    how to get youtube api v3 with volley please teach me

  • Hai Ravi,

    Need small info.

    I want to clear cache of one URL in my app using
    AppController.getInstance().getRequestQueue().getCache().remove(url);

    But what if that URL is paginated. I mean, I’m requesting same URL with different offset and limit when user reaches last item. I’m not sure about the maximum offset user reached.

    So, if i give root URL without any offset and limit, will it clear all previous cache ?

    • 张联

      same problem with you

  • hcbsaab

    Hello Ravi,

    I need help for PATCH requests with volley, can you help?

  • Lee

    i use androidhive as my top reference when create android new project

  • Harish

    HI Ravi,
    Thanks for this tutorial.
    I tried your sample . I am getting null pointer exception.

    java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.htech.volleyandrdhive.app.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)’ on a null object reference
    at com.htech.volleyandrdhive.JsonRequestActivity.makeJsonObjReq(JsonRequestActivity.java:131)
    at com.htech.volleyandrdhive.JsonRequestActivity.onClick(JsonRequestActivity.java:76)

    • Seems you haven’t added AppController in AndroidManifest.xml

  • Luong Long

    amazing topic. But we cant use Param for JsonObjectRequest anymore.
    I needed to use StringRequest instead of JsonRequest.

  • Amigo Madiq

    jsonRequestActivity got error. Method doesn’t override it’s super class.

  • Abdullah Çelik

    hi ravi, Can you share web service codes with us

  • lakshminarayanan

    df

  • lakshminarayanan

    does volley work on 4.4 api???

  • lakshminarayanan

    volley library supprot
    for 4.4??

  • arti

    hello sir i am just starting to learn android i am confuse that i am request server through volley but in doBaground method of asytask is right or not please guide me

    • Hi Arti

      We should always use Async to make http calls. You don’t have to worry about using async as Volley (or other http libraries) internally uses Async only to make the calls.

      • arti

        thank you sir

  • Rajat Gupta

    Hi Ravi,

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

    };

    I didn’t understand the syntax of this Override method “getHeaders()”.
    Can you please explain me the syntax and how to use it .
    Thanks in advance 🙂

  • Shramana Matilal

    Can anybody plz tell me the volley library version for android studio 2.2.2?

  • Sammie

    It’s an amazing post ravi, thanks! But i have a question…What is the problem if we don’t add request headers and post parameters? I got this question because when i just click the link to the json object, a properly structured json response came and i didn’t even pass any parameters.

    • Hi Sammie,

      The header will be required if the services it is connecting insisting some params in header. In your case the json might not need header params, but in real scenario any private REST API require few parameters in headers like Authorization where it needs an api key in header to validate the request.

      • Sammie

        Thanks!

  • Sonu

    Hi ravi

    Can you help with how to get cookies from the header using Volley String Request

    Thanks in advance

    Even params are not etting appended with the request.
    Can you point like what might be wrong.Would be very helpful

    Tried with your sample App to pass params but I got server error

    Following is the request url from debug prespective

    req = {MainActivity$1$3@4435} “[ ] http://api.androidhive.info/volley/person_object.json 0x1fa01c31 NORMAL null”
    this$1 = {MainActivity$1@4433}
    mListener = {MainActivity$1$1@4449}
    mRequestBody = null
    mCacheEntry = null
    mCanceled = false
    mDefaultTrafficStatsTag = 530586673
    mErrorListener = {MainActivity$1$2@4450}
    mEventLog = null
    mMethod = 1
    mRequestQueue = null
    mResponseDelivered = false
    mRetryPolicy = {DefaultRetryPolicy@4451}
    mSequence = null
    mShouldCache = true
    mTag = “AppController”
    mUrl = “http://api.androidhive.info/volley/person_object.json”
    shadow$_klass_ = {Class@307} “class com.example.namratha.sampleandroid.MainActivity$1$3”
    shadow$_monitor_ = -2044946300

    unable to see params
    can you help me out of how to pass params

    Thanks in advance

  • Muhammad Zubair Hasan

    where should I put the code for json request that is in step 2

  • Shuaib Khan

    .hello

  • Shuaib Khan

    i have downloaded your project code and installed in my mobile.its not showing any response after clicking on string request or image request. progress bar show and after that nothing happens. whats the problem plz check your app code again plz and reply me. bro as soon as Possible
    Mr ravi

    https://uploads.disquscdn.com/images/acb32325ba255630af9b83a8c6d838d913e030b3b4d79f0fe37e199baab86912.png

    https://uploads.disquscdn.com/images/7af76d841621f6e251c22985dc6f939ae831d6b0db343e36305094cb0b45041a.png

  • ibrahim nehme

    Hi, I would like to get json data from .NET REST service. The service can be accessed using this url “http://xxx.xxx.x.xxx/Test.Tag.REST/api/User/?EmployeeId=02123&Environment=DEV”. I read your article and would like to use Volley from Android App. What is the best way to do a GET with params? Do I use JsonObjectRequest or StringRequest from volley? and how my end point url will look like? Thanks

  • Philips

    Thank you very much @ravi8x:disqus for this great tutorial, but I just want to ask about using android networking library, which library I should use Retrofit or Volley and why??

    • For now consider Retrofit.

      • Philips

        Thanks bro, but Why do you think Retrofit is better

  • Nikita Vishwakarma

    Amazing

  • rajesh vishwanatham

    hi,
    Individually splash screen and navigation drawer working great…but when trying club both activities in a application , after the splash screen activity the application is getting stopped.

  • Nice!

  • Prateek Batra

    hello @ravi8x:disqus i have POST REQUEST api url something like http://www.example.com/api?parameter1=somevalue&parameter2=samevalue
    so while i try to send parameter using volley post request i am unable to sent the parameters l

  • Ej Castro

    Hi @ravi8x:disqus I am encountering a problem regarding on my Retrofit call. I’m downloading large data estimating 1800 rows. My process is, I have (1800)keys/ids that saved on my local database and created a method that calls the api to get the details of the key and save it again on database. But my application will close when it reaches on 250th row and no errors or warnings display on the logs. Hope you can help me on this. Thanks in advance. – Ej

  • ibrahim

    You have to change the url “http” with “https”. That is why you are getting error that null request queue or empty result.

    • Is it happening while following the article (with http)?

      • ibrahim

        Yes, should write “https”. Also, thanks for this awesome article.

        • Ok. The blog is recently moved to https. Thats why its happening.

  • Rajashri Pawar

    Can we implement SOAP webservices with volley??
    Give me any sample if we can do it.

  • vikas

    confusing tutorial. make it simple for understanding

    • Read it 10 times.

      • Prasanna Kumar

        i can clearly getting this thanks for the good tutorial ravi…

  • jayesh gurudayalani

    Hello Sir..Please help me..I have tried to send request using jsonrequestobject with parameters..I am able to receive parameters on php script and fetch data from database and store that response in file to check and return response but i am facing error this:-Value perfect of type java.lang.String cannot be converted to JSONObject

    php code:-
    0){
    $raw = mysqli_fetch_assoc($result);
    //fwrite($file,(string)json_encode(array(“name”=>$raw[‘name’],”email”=>$raw[’email’])));
    echo json_encode(array(“name”=>$raw[“name”],”email”=>$raw[“email”]));
    }else{

    }

    ?>

    android code:-

    package com.demo.volleyjsondemo;

    import android.content.Context;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;

    import com.android.volley.AuthFailureError;
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.StringRequest;
    import com.demo.volleyjsondemo.Utils.Constants;
    import com.demo.volleyjsondemo.Utils.RequestSingleTone;

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.UnsupportedEncodingException;
    import java.util.HashMap;
    import java.util.Map;

    public class MainActivity extends AppCompatActivity {

    JsonObjectRequest jsonObjectRequest;
    TextView txtName, txtEmail;
    Context context;
    Map parametersMap = new HashMap();

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

    init();
    try {
    sendReq();
    } catch (JSONException e) {
    e.printStackTrace();
    }
    }

    private void init() {
    context = MainActivity.this;
    txtName = (TextView) findViewById(R.id.txtName);
    txtEmail = (TextView) findViewById(R.id.txtEmail);
    }

    private void sendReq() throws JSONException {

    //just to demonstrate how to send parameters with json request
    parametersMap.put(Constants.NAME, “jack”);

    //jsonobjectrequest to send request and get response in json
    jsonObjectRequest = new JsonObjectRequest(
    Request.Method.POST //request method
    , Constants.BASE_URL + Constants.GET_PERSON_DETAILS_URL //URL of php file
    , new JSONObject(parametersMap) //parameters to send to server
    , new Response.Listener() { //response will come here in case of success
    @Override
    public void onResponse(JSONObject response) {
    try {
    Log.e(“response”, “” + response.length());
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    },
    new Response.ErrorListener() { //response will come here in case of error
    @Override
    public void onErrorResponse(VolleyError error) {
    error.printStackTrace();
    }
    });

    //add request to singletone
    RequestSingleTone.getInstance(context).addRequest(jsonObjectRequest);
    }
    }

  • Obi Dever

    Error:Execution failed for task ‘:app:processDebugManifest’.
    > Manifest merger failed : Attribute application@name value=(id.co.belanjaqu.belanjaqu.AppController) from AndroidManifest.xml:24:9-38
    is also present at [com.droidninja:filepicker:1.0.0] AndroidManifest.xml:15:9-64 value=(droidninja.filepicker.FilePickerDelegate).
    Suggestion: add ‘tools:replace=”android:name”‘ to element at AndroidManifest.xml:23:5-350:19 to override.

    hello sir,
    how to fix this?