Android Volley Library Tutorial With Example




Android Volley library is an http library that is used to manage network calls in android. By default, network calls work asynchronously. That means, you do not need to write code for Async Task. By default, it handles everything you need to do while making network calls. It’s easier to use and works faster than most of the libraries. It handles image downloading and uploading, string request, JSON apis such as JSON Array request, JSON object request etc. If you are using Volley library then you do not need to write a ton of code to handle standard way of network calls using HttpURLConnection. The core of every network operation performed by Volley library is RequestQueue. Whenever we need to send a network call, we create a RequestQueue and pass a request object in it. It manages the thread running the network operation, reading from and writing to the cache and finally parsing the response etc.

Some of the important features of Volley library are as follows –
1. Automatic scheduling of network requests.
2. Many concurrent network connections.
3. Transparent memory and disc caching.
4. You can prioritize a request.
5. You can cancel a single request or a set of request at any time.
6. You can easily customize for retry or backoff a request.
7. Built in debugging and tracing tools that makes enable to get the root cause of the error, if any.

How does volley work?

Whenever you want to send a request using volley library , you need to create a request object and pass it in queue. After that, you need to decide how are you going to handle the response. That’s it. You do not need to bother about the task running in the background thread. Whenever network request is fired, it is added to cache queue in the priority order. Then, A cache dispatcher checks whether the response is available in the cache or not. If yes, then, we get response from the cache else an actual server request is sent. When it gets response from the server, then, it sends the response to the main thread.

Source Code

Output

Tutorialwing Android Volley Library Tutorial Output - 1

Tutorialwing Android Volley Library Tutorial Output – 1

Tutorialwing Android Volley Library Tutorial Output - 2

Tutorialwing Android Volley Library Tutorial Output – 2

Video Output

Getting Started

In this tutorial, you will learn about android volley library. Basically, you will learn how to send string request, JSON object request, JSON array request, image downloading, caching, cancelling a request, cancelling a set of request etc. using volley library.

In this tutorial, Following urls will be used.

For String Request –
http://tutorialwing.com/api/tutorialwing_welcome.json

For JSON object Request –
http://tutorialwing.com/api/tutorialwing_details.json

For JSON array Request –
http://tutorialwing.com/api/tutorialwing_posts.json

For Image Downloading –
http://tutorialwing.com/api/tutorialwing_logo.jpg




1. Creating New Project

Follow steps written below to create a new project.
a. Goto File => New => New Project. Then, Write application name as VolleyLibraryTutorial and click next.
b. Select Minimum SDK 17 or more => click next => Select Empty Activity => click next => click finish.
If you have followed above process correctly, you will get a newly created project successfully. If you want to know how to create a project in detail, you can go to Creating First Project

1.1 Basic setup to configure Volley Library

Now, we will do some basic setup to use volley library into our project.

1.1.1 Add gradle into app/build.gradle file
compile 'com.mcxiaoke.volley:library:1.0.19'
1.1.2 Add internet permission into AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
1.1.3 Add code to handle image caching

Create a class LruBitmapCache in com.tutorialwing.volleylibrarytutorial package and add below code into it. It will handle image caching.

package com.tutorialwing.volleylibrarytutorial;

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

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

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);
	}
}
1.1.4 Create a Singleton class to manage request

Now, we will create a custom application class that will act as singleton class and manage network requests. This class will also handle caching and sending request to server etc. Create a class AppController in com.tutorialwing.volleylibrarytutorial package. Add the following code into it.
AppController.java

package com.tutorialwing.volleylibrarytutorial;

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



2. Make various types of network calls

In this tutorial, we will see following network calls using android volley library.

1. String request
2. JSON object request
3. JSON array request
4. Image Downloading

Let’s see the above request one by one.

2.1 Make String request using android volley library

You can send any string request as below

StringRequest stringRequest = new StringRequest(JSON_URL,
		new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				showResponse(response);
			}
		},
		new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Toast.makeText(StringRequestActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
			}
		});

AppController.getInstance().addToRequestQueue(stringRequest, REQUEST_TAG);

We are going to use String request url for this purpose. You can go to this url to check the message.

Example showing string request

We will see an example that shows string request using this library. We will create an activity and xml file for this purpose.

2.1.1 Create activity to send string request using android volley library

Create a StringRequestActivity activity in com.tutorialwing.volleylibrarytutorial package. Add the below code into it.

package com.tutorialwing.volleylibrarytutorial;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

public class StringRequestActivity extends AppCompatActivity {

	public static final String REQUEST_TAG = "STRING_REQUEST_TAG";
	public static final String JSON_URL = "http://tutorialwing.com/api/tutorialwing_welcome.json";

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.string_request_activity);

		View view = findViewById(R.id.get_request);
		if (view != null)
			view.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					sendRequest();
				}
			});
	}

	private void sendRequest() {
		StringRequest stringRequest = new StringRequest(JSON_URL,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						showResponse(response);
					}
				},
				new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Toast.makeText(StringRequestActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
					}
				});

		AppController.getInstance().addToRequestQueue(stringRequest, REQUEST_TAG);
	}

	private void showResponse(String response) {
		TextView txvResponse = (TextView) findViewById(R.id.request_response);
		if (txvResponse != null) {
			txvResponse.setText(response);
		}
	}

}
2.1.2 Create xml file to show string response using android volley library

Also, you need to add a xml file to show output. So, Create an xml file string_request_activity.xml in res => layout folder. Then, add the below code into it.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical"
	android:padding="10dp">

	<LinearLayout
		android:id="@+id/btn_container"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:gravity="center"
		android:orientation="horizontal">

		<Button
			android:id="@+id/get_request"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="@string/get_request"/>

	</LinearLayout>

	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_below="@+id/btn_container"
		android:gravity="center">

		<TextView
			android:id="@+id/request_response"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:gravity="center"/>

	</LinearLayout>

</RelativeLayout>

2.2 JSON array request using android volley library

In this type of request, we get json array as response from server.

You can send json array request as below.

JsonArrayRequest jsonArrayReq = new JsonArrayRequest(JSON_URL,
		new Response.Listener<JSONArray>() {
			@Override
			public void onResponse(JSONArray response) {
				showResponse(new Posts(response));
			}
		},
		new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
			}
		});
// Adding JsonObject request to request queue
AppController.getInstance().addToRequestQueue(jsonArrayReq, REQUEST_TAG);

You can see the json in JSON URL. We will be doing this in following steps.

Example showing JSON array request

We are using RecyclerView to show response as list. If you do not know how to use recyclerView, you can visit RecyclerView Tutorial Part 1 and RecyclerView Tutorial Part 2.

So, we will first create models, adapter for recyclerView etc. After that, we will send the actual request.

2.2.1 Create models

Create models folder in com.tutorialwing.volleylibrarytutorial package. Now, create two model classes(Post.java and Posts.java) in it. Add the below code into it.
Posts.java

package com.tutorialwing.volleylibrarytutorial.models;

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

import java.util.ArrayList;
import java.util.List;
public class Posts {
	private List<Post> posts;
	public Posts(JSONArray jsonArray) {
		parseJson(jsonArray);
	}
	private void parseJson(JSONArray jsonArray) {
		posts = new ArrayList<>();
		for (int i = 0; i < jsonArray.length(); i++) {
			try {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				posts.add(new Post(jsonObject));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	public List<Post> getPosts() {
		return posts;
	}
}

Post.java

package com.tutorialwing.volleylibrarytutorial.models;

import com.tutorialwing.volleylibrarytutorial.Constants;

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

public class Post {

	private String name;
	private String title;
	private String category;
	private String url;

	public Post(JSONObject jsonObject) {
		parseJson(jsonObject);
	}
	private void parseJson(JSONObject jsonObject) {
		try {
			name = jsonObject.getString(Constants.KEY_NAME);
			title = jsonObject.getString(Constants.KEY_TITLE);
			category = jsonObject.getString(Constants.KEY_CATEGORY);
			url = jsonObject.getString(Constants.KEY_URL);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	public String getName() {
		return name;
	}
	public String getTitle() {
		return title;
	}
	public String getCategory() {
		return category;
	}
	public String getUrl() {
		return url;
	}
}

Note: We have also added a parseJson() method to show json parsing. please have a look into it.

2.2.2 Create adapter for RecyclerView

Add adapter for the recyclerView. Create PostAdapter in com.tutorialwing.volleylibrarytutorial package. Add the below code into it.

package com.tutorialwing.volleylibrarytutorial;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.tutorialwing.volleylibrarytutorial.models.Post;
import com.tutorialwing.volleylibrarytutorial.models.Posts;

import java.util.List;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {

	private List<Post> posts;
	private int rowLayout;

	public PostAdapter(Posts posts, int rowLayout) {
		this.posts = posts.getPosts();
		this.rowLayout = rowLayout;
	}

	@Override
	public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
		return new PostViewHolder(view);
	}

	@Override
	public void onBindViewHolder(PostViewHolder holder, final int position) {
		holder.name.setText(posts.get(position).getName());
		holder.title.setText(posts.get(position).getTitle());
		holder.category.setText(posts.get(position).getCategory());
		holder.url.setText(posts.get(position).getUrl());
	}

	@Override
	public int getItemCount() {
		return posts.size();
	}

	static class PostViewHolder extends RecyclerView.ViewHolder {
		TextView name;
		TextView title;
		TextView category;
		TextView url;

		PostViewHolder(View v) {
			super(v);
			name = (TextView) v.findViewById(R.id.name);
			title = (TextView) v.findViewById(R.id.title);
			category = (TextView) v.findViewById(R.id.category);
			url = (TextView) v.findViewById(R.id.url);
		}
	}
}
2.2.3 Create layout for single Item

Now, create an xml file to show how a single item will look. So, create single_post.xml file in res => layout folder. Add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:background="#f0f0f0"
	android:orientation="vertical"
	android:padding="2dp">

	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:background="@android:color/white"
		android:orientation="vertical"
		android:padding="4dp">

		<TextView
			android:id="@+id/name"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_marginBottom="5dp"
			android:textSize="20sp"
			android:textStyle="bold"/>

		<TextView
			android:id="@+id/title"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_marginBottom="5dp"/>

		<TextView
			android:id="@+id/category"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_marginBottom="5dp"/>

		<TextView
			android:id="@+id/url"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"/>

	</LinearLayout>

</LinearLayout>
2.2.4 Create activity to send json array request using android volley library

Create a JsonArrayRequestActivity activity in com.tutorialwing.volleylibrarytutorial package. Add below code into it.

package com.tutorialwing.volleylibrarytutorial;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.tutorialwing.volleylibrarytutorial.models.Posts;

import org.json.JSONArray;

public class JsonArrayRequestActivity extends AppCompatActivity implements View.OnClickListener {

	public static final String REQUEST_TAG = "JSON_ARRAY_REQUEST_TAG";
	public static final String JSON_URL = "http://tutorialwing.com/api/tutorialwing_posts.json";

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.json_array_request_activity);

		View view = findViewById(R.id.get_request);
		if (view != null)
			view.setOnClickListener(this);
	}

	private void sendRequest() {
		JsonArrayRequest jsonArrayReq = new JsonArrayRequest(JSON_URL,
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {
						showResponse(new Posts(response));
					}
				},
				new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
					}
				});

		// Adding JsonObject request to request queue
		AppController.getInstance().addToRequestQueue(jsonArrayReq, REQUEST_TAG);
	}

	private void showResponse(Posts posts) {
		RecyclerView recyclerView = (RecyclerView) findViewById(R.id.request_response);
		if (recyclerView != null) {
			PostAdapter postAdapter = new PostAdapter(posts, R.layout.single_post);
			recyclerView.setLayoutManager(new LinearLayoutManager(this));
			recyclerView.setAdapter(postAdapter);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.get_request:
				sendRequest();
				break;
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		AppController.getInstance().getRequestQueue().cancelAll(REQUEST_TAG);
	}
}
2.2.5 Create xml file to show json array response using android volley library

Create an xml file json_array_request_activity.xml in res => layout folder. Add the below code into it.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical"
	android:padding="10dp">
	<LinearLayout
		android:id="@+id/btn_container"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:gravity="center"
		android:orientation="horizontal">
		<Button
			android:id="@+id/get_request"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="@string/fetch_data"/>
	</LinearLayout>
	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_below="@+id/btn_container"
		android:gravity="center">
		<android.support.v7.widget.RecyclerView
			android:id="@+id/request_response"
			android:layout_width="match_parent"
			android:layout_height="match_parent"/>
	</LinearLayout>
</RelativeLayout>



2.3 JSON object request using android volley library

In this type of request, you get a single object as response. You can send any JSON object request as below.

JsonObjectRequest jsonObjectReq = new JsonObjectRequest(JSON_URL, null,
		new Response.Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				showResponse(response, "Showing GET request response...");
			}
		},
		new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
			}
		});
// Adding JsonObject request to request queue
AppController.getInstance().addToRequestQueue(jsonObjectReq, REQUEST_TAG);
Sending Headers parameter in request

You can send parameters in headers as below.

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, JSON_URL,
		new Response.Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				showResponse(response, "Showing POST request response...");
			}
		},
		new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
//				VolleyLog.d(TAG, "Error: " + error.getMessage());
			}
		}) {
	// You can send parameters as header with POST request....
	@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;
	}
};
AppController.getInstance().addToRequestQueue(jsonObjReq, POST_REQUEST_TAG);

Similarly, you can send headers parameter with any request such as GET, POST, JSON array request, request to download image etc.

Sending parameters in post request

You can send parameters in post request as below.

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, JSON_URL,
		new Response.Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				showResponse(response, "Showing POST request response...");
			}
		},
		new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
//				VolleyLog.d(TAG, "Error: " + error.getMessage());
			}
		}) {
	// You can send parameters as well with POST request....
	@Override
	protected Map<String, String> getParams() {
		Map<String, String> params = new HashMap<>();
		params.put("name", "Tutorialwing");
		params.put("email", "tutorialwing@gmail.com");
		params.put("password", "1234567");
		return params;
	}

Similarly, you can send parameters, if any, with any request such as GET, POST, Json object request, Json array request, request to download image etc.

We are going to use JSON Object Url to show an example to send JSON object request. You can check the json file if you want.

Example showing JSON object request

Now, We will see an example to send and receive Json object request using android volley library.

2.3.1 Create activity to show JSON object, GET and POST request using android volley library

Create an activity JsonObjectRequestActivity.java in com.tutorialwing.volleylibrarytutorial package. Add the below code into it. Here, we have also shown how to send GET and POST request using volley library. Finally, activity class will look like below.

package com.tutorialwing.volleylibrarytutorial;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
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.tutorialwing.volleylibrarytutorial.models.Tutorialwing;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class JsonObjectRequestActivity extends AppCompatActivity implements View.OnClickListener {

	public static final String REQUEST_TAG = "JSON_OBJECT_REQUEST_TAG";
	public static final String POST_REQUEST_TAG = "JSON_OBJECT_POST_REQUEST_TAG";
	public static final String JSON_URL = "http://tutorialwing.com/api/tutorialwing_details.json";

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.json_object_request_activity);

		View view = findViewById(R.id.get_request);
		if (view != null)
			view.setOnClickListener(this);

		view = findViewById(R.id.post_request);
		if (view != null)
			view.setOnClickListener(this);
	}

	private void sendRequest() {
		JsonObjectRequest jsonObjectReq = new JsonObjectRequest(JSON_URL, null,
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						showResponse(response, "Showing GET request response...");
					}
				},
				new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
					}
				});

		// Adding JsonObject request to request queue
		AppController.getInstance().addToRequestQueue(jsonObjectReq, REQUEST_TAG);
	}

	private void sendPostRequest() {

		// Change the url of the post request as per your need...This url is just for demo purposes and
		// actually it does not post data...i.e. it will return same response irrespective of the value you
		// as parameters.

		JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, JSON_URL,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						showResponse(response, "Showing POST request response...");
					}
				},
				new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
//						VolleyLog.d(TAG, "Error: " + error.getMessage());
					}
				}) {

			// You can send parameters as well with POST request....
			@Override
			protected Map<String, String> getParams() {
				Map<String, String> params = new HashMap<>();
				params.put("name", "Tutorialwing");
				params.put("email", "tutorialwing@gmail.com");
				params.put("password", "1234567");
				return params;
			}
		};

		AppController.getInstance().addToRequestQueue(jsonObjReq, POST_REQUEST_TAG);
	}

	private void sendPostRequestWithHeaders() {

		// Change the url of the post request as per your need...This url is just for demo purposes and
		// actually it does not post data...i.e. it will return same response irrespective of the value you
		// as parameters.

		JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, JSON_URL,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						showResponse(response, "Showing POST request response...");
					}
				},
				new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
//						VolleyLog.d(TAG, "Error: " + error.getMessage());
					}
				}) {

			// You can send parameters as header with POST request....
			@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;
			}
		};

		AppController.getInstance().addToRequestQueue(jsonObjReq, POST_REQUEST_TAG);
	}

	private void showResponse(JSONObject response, String extra_info) {
		Tutorialwing tutorialwing = new Tutorialwing(response);
		String text = extra_info
				+ "\n\n Website: " + tutorialwing.getWebsite()
				+ "\n\n Topics: " + tutorialwing.getTopics()
				+ "\n\n Facebook: " + tutorialwing.getFacebook()
				+ "\n\n Twitter: " + tutorialwing.getTwitter()
				+ "\n\n Pinterest: " + tutorialwing.getPinterest()
				+ "\n\n Youtube: " + tutorialwing.getYoutube()
				+ "\n\n Message: " + tutorialwing.getMessage();

		TextView txvResponse = (TextView) findViewById(R.id.request_response);
		if (txvResponse != null) {
			txvResponse.setText(text);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.get_request:
				sendRequest();
				break;
			case R.id.post_request:
				sendPostRequest();
				break;
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		AppController.getInstance().getRequestQueue().cancelAll(REQUEST_TAG);
	}
}
2.3.2 Create xml file to show JSON object GET and POST response using android volley library

You also need to create an xml file to show response. Create an xml file json_object_request_activity.xml in res => layout folder. Add the below code into it.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical"
	android:padding="20dp">
	<LinearLayout
		android:id="@+id/btn_container"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:gravity="center"
		android:orientation="horizontal">
		<Button
			android:id="@+id/get_request"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="@string/get_request"/>
		<Button
			android:id="@+id/post_request"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="@string/post_request"/>
	</LinearLayout>
	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_below="@+id/btn_container"
		android:gravity="center">
		<TextView
			android:id="@+id/request_response"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"/>
	</LinearLayout>
</RelativeLayout>



2.4 Image downloading and caching using android volley library

You can easily download and cache image using volley library. You can download image and show into imageView. You can also use NetworkImageView, provided by volley library, to show downloaded image. Let’s see how can you download image and show in different views.

Download image and show into ImageView

You can download and show image into imageView as below.

ImageLoader imageLoader = AppController.getInstance().getImageLoader();
imageLoader.get(IMAGE_URL, new ImageLoader.ImageListener() {
	@Override
	public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
		showResponse(response);
	}
	@Override
	public void onErrorResponse(VolleyError error) {
		// Add code to perform action when error occured.
	}
});
Download image and show into ImageView with placeholder and error image

You can show placeholder and error image while downloading image from the server as below.

ImageLoader imageLoader = AppController.getInstance().getImageLoader();
if (imageView != null) {
	// Loading image with placeholder and error image
	imageLoader.get(IMAGE_URL, ImageLoader.getImageListener(imageView, R.drawable.ic_placeholder, R.drawable.error));
}
Download image and show into NetworkImageView

You can also use NetworkImageView, provided by Volley library, to download and show image. You can do it as below.

ImageLoader imageLoader = AppController.getInstance().getImageLoader();
if (networkImageView != null) {
	networkImageView.setImageUrl(IMAGE_URL, imageLoader);
}
Example showing server request to download image, cache it and show into ImageView and NetworkImageView

We will see an example to download and cache image. Then, we will see to show this image into ImageView and NetworkImageView.

2.4.1 Create activity to manage image request

Create an activity ImageActivity.java in com.tutorialwing.volleylibrarytutorial package. Activity will manage the network calls while xml file is needed to show the output i.e. image downloaded from server. Add below code into it.

package com.tutorialwing.volleylibrarytutorial;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

public class ImageActivity extends AppCompatActivity implements View.OnClickListener {

	public static final String IMAGE_URL = "http://tutorialwing.com/api/tutorialwing_logo.jpg";

	private ImageView imageView;
	private ImageView imageViewWithPlaceholderAndError;
	private NetworkImageView networkImageView;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.image_activity);

		View view = findViewById(R.id.load_image);
		if (view != null)
			view.setOnClickListener(this);

		view = findViewById(R.id.load_network_image);
		if (view != null)
			view.setOnClickListener(this);

		view = findViewById(R.id.load_image_placeholder_error);
		if (view != null)
			view.setOnClickListener(this);

		imageView = (ImageView) findViewById(R.id.image_view);
		imageViewWithPlaceholderAndError = (ImageView) findViewById(R.id.image_view_placeholder_error);
		networkImageView = (NetworkImageView) findViewById(R.id.network_image_view);
	}

	private void sendRequest() {
		ImageLoader imageLoader = AppController.getInstance().getImageLoader();
		imageLoader.get(IMAGE_URL, new ImageLoader.ImageListener() {
			@Override
			public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
				showResponse(response);
			}

			@Override
			public void onErrorResponse(VolleyError error) {
				// Add code to perform action when error occured.
			}
		});
	}

	private void showResponse(ImageLoader.ImageContainer response) {
		if (imageView != null) {
			imageView.setImageBitmap(response.getBitmap());
		}
	}

	private void loadImageWithPlaceholderAndError() {
		ImageLoader imageLoader = AppController.getInstance().getImageLoader();
		if (imageViewWithPlaceholderAndError != null) {
			// Loading image with placeholder and error image
			imageLoader.get(IMAGE_URL, ImageLoader.getImageListener(imageViewWithPlaceholderAndError, R.mipmap.ic_launcher, R.drawable.error));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.load_image:
				sendRequest();
				break;
			case R.id.load_image_placeholder_error:
				loadImageWithPlaceholderAndError();
				break;
			case R.id.load_network_image:
				ImageLoader imageLoader = AppController.getInstance().getImageLoader();
				if (networkImageView != null) {
					networkImageView.setImageUrl(IMAGE_URL, imageLoader);
				}
				break;
		}
	}
}
2.4.2 Create xml file to show image into image view, NetworkImageView

Now, create an xml file image_activity.xml into res => layout folder. Add below code into it.
image_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent">
	<RelativeLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:orientation="vertical"
		android:padding="10dp">
		<LinearLayout
			android:id="@+id/image_container"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_marginBottom="10dp"
			android:orientation="vertical">
			<Button
				android:id="@+id/load_image"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_marginBottom="10dp"
				android:text="@string/load_image_into_imageview"
				android:textAllCaps="false"/>

			<ImageView
				android:id="@+id/image_view"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:contentDescription="@string/imageview"/>
		</LinearLayout>
		<LinearLayout
			android:id="@+id/image_with_placeholder_container"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/image_container"
			android:layout_marginBottom="10dp"
			android:orientation="vertical">
			<Button
				android:id="@+id/load_image_placeholder_error"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_marginBottom="10dp"
				android:text="@string/load_image_with_placehodler_error_into_imageview"
				android:textAllCaps="false"/>
			<ImageView
				android:id="@+id/image_view_placeholder_error"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:contentDescription="@string/imageview"/>
		</LinearLayout>
		<LinearLayout
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/image_with_placeholder_container"
			android:orientation="vertical">
			<Button
				android:id="@+id/load_network_image"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_marginBottom="10dp"
				android:text="@string/load_image_into_networkimageview"
				android:textAllCaps="false"/>
			<com.android.volley.toolbox.NetworkImageView
				android:id="@+id/network_image_view"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"/>
		</LinearLayout>
	</RelativeLayout>
</ScrollView>



3. Advance concepts about android volley library

Till now, we have seen basic things about volley library. Now, we will see advance concepts about volley library. Some topics that we are going to discuss is –
Manage Caching
Request cancellation
Request prioritization

3.1 Manage Caching in volley library

In this section, we will see how to handle caching using volley library.

3.1.1 Load response of any request from cache
RequestQueue requestQueue = AppController.getInstance().getRequestQueue();
if (requestQueue != null) {
	Cache cache = requestQueue.getCache();
	if (cache != null) {
		Cache.Entry entry = cache.get(JSON_URL);
		if (entry != null) {
			// Handle the data here....
		} else {
			// data is not present in the cache..so send server request...
		}
	}
}
3.1.2 Invalidate the cache

If you do not want to delete the data present in the cache, instead of it, you want to invalidate the cache. You can do it as below. Later on, when data comes from the server, it will replace the old data present in the cache.

RequestQueue requestQueue = AppController.getInstance().getRequestQueue();
if (requestQueue != null) {
	Cache cache = requestQueue.getCache();
        if(cache != null) {
              cache.invalidate(URL, true);
        }
}
3.1.3 Deleting cached data for any url

If you want to delete any cached data, you can do it as below.

RequestQueue requestQueue = AppController.getInstance().getRequestQueue();
if (requestQueue != null) {
	Cache cache = requestQueue.getCache();
        if(cache != null) {
              cache.remove(URL);
        }
}
3.1.4 Deleting all cached data

If you want to delete all cached data, you can do it as below.

RequestQueue requestQueue = AppController.getInstance().getRequestQueue();
if (requestQueue != null) {
	Cache cache = requestQueue.getCache();
        if(cache != null) {
              cache.clear(URL);
        }
}
3.1.5 Disable caching for any particular url

If you want to disable caching for any url, you can do it as below.

JsonObjectRequest jsonObjReq = new JsonObjectRequest(...);
jsonObjReq.setShouldCache(false);

3.2 Cancel Requests in volley library

You can cancel a particular request or all request at any time using volley library.Remember…. We are sending REQUEST_TAG with every request. We will use that tag to detect the request to cancel. However, if you want to cancel all request, you don’t need to use TAG. You just call cancelAll() method. That’s it.

To cancel a particular request

RequestQueue requestQueue = AppController.getInstance().getRequestQueue();
if (requestQueue != null) {
	requestQueue.cancelAll(REQUEST_TAG);
}

To cancel all requests

RequestQueue requestQueue = AppController.getInstance().getRequestQueue();
if (requestQueue != null) {
	requestQueue.cancelAll();
}

3.3 Request prioritization in android volley library

You can set priority of any request while making network calls using volley library. The allowed priorities are NORMAL, LOW, IMMEDIATE and HIGH. You can set request priority as below.

final Request.Priority priority = Request.Priority.HIGH;
StringRequest strReq = new StringRequest(Request.Method.GET,
		REQUEST_URL, new Response.Listener<String>() {

	@Override
	public void onResponse(String response) {
		// Handle the response here.....
	}
}, new Response.ErrorListener() {

	@Override
	public void onErrorResponse(VolleyError error) {
		// Handle the error here....
	}
}) {
	@Override
	public Priority getPriority() {
		return priority;
	}
};



Output

If you run the application, you will get output as given above. If you have any questions or got some problems while following this tutorial, you can download the source code as well. Source code link is already given above.

Conclusion

Android Volley library is an easy to configure and use to manage network calls in Android. You just need to add some few lines to code and you are done. You will get output as desired. You can send Asynchronous calls using this library too. You can send GET, POST, PUT, DELETE any type of requests as well. You can send string request, json object request, json array request or image request too. However, There is also another popular library(Android Retrofit Library) that can be used to manage network calls. You can use either one as per your need. Both libraries have some advantages and dis-advantages. So, which one to use depends on your need.

Support Us

If you have any suggestion about this post, please comment below. We are looking for someone who helps use to make our tutorial better. Also, If you want tutorials on any topic, you can mail us at tutorialwing@gmail.com. We will try to cover the topic as soon as possible. Connect with us on Facebook, Google+, Twitter and Youtube for more updates.

  • I want to do same but for a nested json array response
    Can you help me out with making of its adapter. And models

    • Replied to your queries on facebook page.. 😉