Android Volley Tutorial – Making HTTP GET, POST, PUT

Google released Android Volley Library around May/June 2013, which has been internally used by Google for some time. It is supposed to provide Fast Networking Operations and also takes care of Threads nicely. If you are unfamiliar with Volley, please see Google I/O 2013 Video

Unfortunately, there is almost no documentation on Volley. So, I put together code snippets on how to make Volley HTTP Requests (GET, POST, PUT, DELETE).

Setting up Android Volley Library

Setting up is straight-forward. Clone the Volley project from here and then import the Volley into project. A comprehensive tutorial on setting up can be found here.

Key Classes of Android Volley

The following are the Key classes of Volley:

  • – RequestQueue: A Queue containing the Network/HTTP Requests that needs to be made.
  • – Request: A Base Class which contains Network related information like HTTP Methods.
  • – StringRequest: HTTP Request where the response is parsed a String. View Source
  • – JsonObjectRequest: HTTP Request where the response is JSONObject. View Source

Getting Started with Android Volley

At first make a RequestQueue, which holds the HTTP Requests. View Source. Ideally, the RequestQueue should be made once and then referred to it across the Application. The Application is an ideal place to make it.

RequestQueue queue = Volley.newRequestQueue(this);  // this = context

Making GET Requests

Making GET Requests is simple. The example below uses JsonObjectRequest. It prepares a JsonObjectRequest and
passes and then adds it to RequestQueue. The JsonObject accepts 4 parameters (Http method, Url, Json values, Response Listener – Invoked on success, Error Listener – Invoked on failure).


final String url = "http://httpbin.org/get?param1=hello";

// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
	new Response.Listener<JSONObject>() 
	{
		@Override
		public void onResponse(JSONObject response) {	
                        // display response		
			Log.d("Response", response.toString());
		}
	}, 
	new Response.ErrorListener() 
	{
		 @Override
		 public void onErrorResponse(VolleyError error) {			 
			Log.d("Error.Response", response);
	   }
	}
);

// add it to the RequestQueue	
queue.add(getRequest);

Making POST Requests

For a POST request, to add form parameters/values, the getParams() method needs to be overridden and a Map needs to be returned.

url = "http://httpbin.org/post";
StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
	new Response.Listener<String>() 
	{
		@Override
		public void onResponse(String response) {
			// response
			Log.d("Response", response);
		}
	}, 
	new Response.ErrorListener() 
	{
		 @Override
		 public void onErrorResponse(VolleyError error) {
			 // error
			 Log.d("Error.Response", response);
	   }
	}
) {		
	@Override
	protected Map<String, String> getParams() 
	{  
			Map<String, String>  params = new HashMap<String, String>();  
			params.put("name", "Alif");  
			params.put("domain", "http://itsalif.info");
			
			return params;  
	}
};
queue.add(postRequest);

Making PUT Requests

Creating PUT Request is same as POST basically.

url = "http://httpbin.org/put";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url, 
	new Response.Listener<String>() 
	{
		@Override
		public void onResponse(String response) {
			// response
			Log.d("Response", response);
		}
	}, 
	new Response.ErrorListener() 
	{
		 @Override
		 public void onErrorResponse(VolleyError error) {
                         // error
			 Log.d("Error.Response", response);
	   }
	}
) {

	@Override
	protected Map<String, String> getParams() 
	{  
			Map<String, String>  params = new HashMap<String, String> ();  
			params.put("name", "Alif");  
			params.put("domain", "http://itsalif.info");
			
			return params;  
	}

};

queue.add(putRequest);

Making DELETE Requests

url = "http://httpbin.org/delete";
StringRequest dr = new StringRequest(Request.Method.DELETE, url, 
	new Response.Listener<String>() 
	{
		@Override
		public void onResponse(String response) {
			// response
			Toast.makeText($this, response, Toast.LENGTH_LONG).show();
		}
	}, 
	new Response.ErrorListener() 
	{
		 @Override
		 public void onErrorResponse(VolleyError error) {
			 // error.
			 
	   }
	}
);
queue.add(dr);

Hope it helps!

Android activity hide action bar

If the Action bar of an Android’s activity needs to be hidden through the manifest xml file (non Java Programming), then the easy way is to add the following attribute in Activity tag:

android:theme="@style/Theme.NoActionBar"

However, if a custom Theme is created then it is convenient to create another style extending the custom theme and then adding the following two items in it.

        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>

Suppose, the default theme is called MyTheme, then we create a new Theme called NoActionBar, and add the following two items.

<style name="NoActionBar" parent="MyTheme">
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
</style>

Then, simply refer by using the NoActionBar Theme

android:theme="@style/NoActionBar"

Check Database exist fails android sqlite3openv2

I developed an android application where I shipped an sqlite database with the application. The Sqlite is initially stored at assets folder, and then copied to the proper directory (/data/data/[package]/databases/[db-name]) upon launch. I had the following piece of code for checking the existence of a database.

	public boolean databaseExist()
	{
		SQLiteDatabase checkDB = null;
		try {
			checkDB = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
			checkDB.close();
			return true;
		}
		catch(SQLiteException e) {
			// Log an info message stating database doesn't exist.
		}
		
		return false;
	}

Even though I was catching an exception, however, I was still getting the error message (sqlite3_open_v2 failed):

sqlite3_open_v2("...',  &handle, 6, NULL) open failed

Doing some googling shows that its a popular problem.

Finally, I tried an old school java code with java.io.File, and then it seemed to work fine. So I modified the code like below:

public boolean databaseExist()
{
	File dbFile = new File(DB_PATH + DB_NAME);
	return dbFile.exists();
}

And, it works very well, I also noticed this appears to be somewhat faster than the previous openDatabase approach

I hope this helps someone out.

jFile Chopper: A File Chopper Program using Java

This is a program i created back in 2005, during my initial years on Java. Its a simple program that allows you to chop any files, into smaller segments. You can specify the number of segments you wish to chop into. For example, if you have a 50mb file, you can split it into 5 different files, with each being 10 mb in size. You can then again use the program to merge the files into a large files.

This program also allows you to create a separate batch file (for Windows), so, if you are using Windows, you can split the files, and then you don’t even need the program the merge it. You can simply run the batch file to merge the splitted segments into the large original file.

Here’s the screenshot:

jFile Chopper Grab

ZIP File has been provided with details. Unzip the chopper.zip file and run the mainFrame.jar file. 😉