Friday, February 21, 2014

Dynamic ListView: AsyncTask Comparison by JFrankie

In this post, I will describe first how to use Volley to populate dynamically a ListView, and then compare it against AsycnTask.

In this post, we 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 want to obtain something like the image shown below:

We have already covered this topic in a previous post, and this is the chance to underline the different approaches (Volley and AsyncTask).

Volley JSONArrayRequest


Inside Volley, there is 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:

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

}
});



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:

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


At the end, we set the new contact list in our adapter and call:

No comments:

Post a Comment