This post describes how to populate Android ListView using Volley. In more details, this tutorial describes how to use Android Volley to populate dynamically a ListView using JSON, and then compare it against AsycnTask.
To get data, the Android app will invoke a remote service to get contact information in JSON format. and we populate the items inside a ListView.This simple example is very useful to understand Volley library and how we can integrate it.
We have already covered this topic in a previous post, and this is the chance to underline the different approaches (Volley and AsyncTask).

We want to obtain something like the image shown below:
Populate Android ListView using Volley with JSONArrayRequest
Android Volley lib provides a class called JsonArrayRequest, that can be used to retrieve JSON Array as response. As always, we have two different listener; we have to implement:
- one to get the response
- another one to handle errors
The source code is shown below:
[java]JsonArrayRequest jReq = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
List<Contact> result = new ArrayList<Contact>();
for (int i = 0; i < response.length(); i++) {
try {
result.add(convertContact(response
.getJSONObject(i)));
} catch (JSONException e) {
}
}
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
[/java]
In onResponse method, we have a JSONArray object that holds the response. In this method, we traverse the json array and convert json data to Contact object, using convert method:
[java]private final Contact convertContact(JSONObject obj) throws JSONException {String name = obj.getString(“name”);
String surname = obj.getString(“surname”);
String email = obj.getString(“email”);
String phoneNum = obj.getString(“phoneNum”);
return new Contact(name, surname, email, phoneNum);
}
[/java]
At the end, we set the new contact list in our adapter and call:
[java]adpt.notifyDataSetChanged();[/java]Volley vs AsyncTask
Now we are ready to compare Volley lib against AsycnTask. As we already know, AsyncTask have some problems regarding memory leaks, so we have to use it carefully.Volley doesn’t have such problems and we can use it every time we need to access to a remote resource.Moreover, Volley simplify the code we have to write to invoke a remote service. In the code below, I show these two different approaches:
[java]private class AsyncListViewLoader extends AsyncTask<String, Void, List<Contact>> {private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPostExecute(List<Contact> result) {
super.onPostExecute(result);
dialog.dismiss();
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage(“Downloading contacts…”);
dialog.show();
}
@Override
protected List<Contact> doInBackground(String… params) {
List<Contact> result = new ArrayList<Contact>();
try {
URL u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod(“GET”);
conn.connect();
InputStream is = conn.getInputStream();
// Read the stream
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ( is.read(b) != -1)
baos.write(b);
String JSONResp = new String(baos.toByteArray());
JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
result.add(convertContact(arr.getJSONObject(i)));
}
return result;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
}[/java]
[java]RequestQueue rq = Volley.newRequestQueue(this);
JsonArrayRequest jReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
List<Contact> result = new ArrayList<Contact>();
for (int i = 0; i < response.length(); i++) {
try {
result.add(convertContact(response
.getJSONObject(i)));
} catch (JSONException e) {
}
}
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(jReq);[/java]
It is clear that using Volley we have less code lines to write and we don’t have to worry about handling HTTP connection.
Android HTTP Client: GET, POST, Download, Upload, Multipart Request
Android Apache HTTP Client
Android AsyncTask ListView -JSON
Thank you so much for this tutorial! you saved my time!
If you have complicated logic in convertContact, would it be better to use async task? Since onResponse run on main thread
What is adpt?
Sounds like an Adapter. Perhaps a ArrayAdapter, or a BaseAdapter, SimpleAdapter, CursorAdapter, or something. But none of those seem to contain the method setItemList() so I don't know.
Adpt is a custom adapter. This adapter extends ArrayAdapter I will add the project to github soon. Anyway:
public class SimpleAdapter extends ArrayAdapter {
…..
public void setItemList(List itemList) {
this.itemList = itemList;
}
..
}
Very useful info, can you please provide full example of this tutorial. Thanks.
Very useful info, can you please provide full example of this tutorial. Thanks.
what to put in url
what to put in url
how can I use volley with utf-8 ? can you give example with implementation , thanks
how can I use volley with utf-8 ? can you give example with implementation , thanks
please can any one explain (with code) how to retreive data from a sql table in view these data in android.please post the php code and android as well.thanks
If the data is stored in a table in Android you could use a Cursor to read it or if it doesn’t contain many rows you could simply read the table and store them in an array. If the database is stored in a remote server you can implement a Webservice that reads it and returns the data.
hi i want to ask about your code
obj.getString(“name”);#sthash.o1Kk6Nqu.dpufobj.getString(“name”);
where did you get the “name” object , is that from json ?
thankyou
obj.getString(“name”);#sthash.o1Kk6Nqu.dpuf
obj.getString(“name”);#sthash.o1Kk6Nqu.dpuf