Many times we need to populate Android Listview using AsyncTask. This is the case when we have to invoke a remote server and exchange information using JSON.
In this post, I want to go a bit deeper into the ListView analysis. In the previous posts, I described how to use ListView in several ways using standard and custom adapters. In all the example I’ve supposed to have a fixed items set. In this post, I will describe how it is possible to retrieve items directly from JEE Server.
To make things simple let’s suppose we have a simple JEE server that manages some contacts. Our contact is made by
- name
- surname,
- phone number
How to make this server is out of the scope of this post and I will simply make available the source code. Just to give you some details, I can say that the server is a JEE server developed using RESTFul web services (in our case jersey API).
In this case, the app behaves like a client that invokes the remote service to get the contacts list and show it using the ListView. The data sent from the server to the client is formatted using JSON.
Here you can download the source code:
Implement Android AsyncTask ListView
As always we start creating our custom adapter, that uses a custom layout. If you need more information about creating a custom adapter you can give a look here and here. Here’s the code:
[java]public class SimpleAdapter extends ArrayAdapter<Contact> {private List<Contact> itemList;
private Context context;
public SimpleAdapter(List<Contact> itemList, Context ctx) {
super(ctx, android.R.layout.simple_list_item_1, itemList);
this.itemList = itemList;
this.context = ctx;
}
public int getCount() {
if (itemList != null)
return itemList.size();
return 0;
}
public Contact getItem(int position) {
if (itemList != null)
return itemList.get(position);
return null;
}
public long getItemId(int position) {
if (itemList != null)
return itemList.get(position).hashCode();
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, null);
}
Contact c = itemList.get(position);
TextView text = (TextView) v.findViewById(R.id.name);
text.setText(c.getName());
TextView text1 = (TextView) v.findViewById(R.id.surname);
text1.setText(c.getSurname());
TextView text2 = (TextView) v.findViewById(R.id.email);
text2.setText(c.getEmail());
TextView text3 = (TextView) v.findViewById(R.id.phone);
text3.setText(c.getPhoneNum());
return v;
}
public List<Contact> getItemList() {
return itemList;
}
public void setItemList(List<Contact> itemList) {
this.itemList = itemList;
}
}[/java]
By now everything is smooth and easy.
How to develop an HTTP Client to retrieve data form ListView Adapter
One thing we need to do is creating our HTTP client in order to make a request to the JEE server. As we all know an HTTP request can require a long time before the answer is available, so we need to take this into the account so that Android OS won’t stop our application. The simplest thing is using Android AsyncTask listview, or in more details, creating an AsyncTask that makes this request and waits for the response.
[java] private class AsyncListViewLoader extendsAsyncTask<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;
}
private 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]
Let’s analyze the code.
In the initial step (onPreExecute()) before the task starts we simply show a dialog to inform the user that the app is downloading the contact list. The most interesting part is in the doInBackground method where the app makes the HTTP connection. We first create an HTTPConnection and set the GET method like that:
[java]HttpURLConnection conn = (HttpURLConnection) u.openConnection();conn.setRequestMethod(“GET”);
conn.connect();
[/java]
Afterward, we have to create an input stream and then read the byte stream:
[java]InputStream is = conn.getInputStream();// Read the stream
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ( is.read(b) != -1)
baos.write(b);
[/java]
Now we have all the stream in our byte array and we need simply parse it using JSON.
[java]JSONArray arr = new JSONArray(JSONResp);for (int i=0; i<arr.length(); i++) {
result.add(convertContact(arr.getJSONObject(i)));
}
return result;
[/java]
Done! What’s next?…Well we need to inform the adapter that we’ve a new contact list and it has to show it. We can do it in the onPostExecute(List<Contact> result) where:
[java]super.onPostExecute(result);dialog.dismiss();
adpt.setItemList(result);
adpt.notifyDataSetChanged();[/java]
And finally in the onCreate method we have:
[java] public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adpt = new SimpleAdapter(new ArrayList(), this);
ListView lView = (ListView) findViewById(R.id.listview);
lView.setAdapter(adpt);
// Exec async load task
(new AsyncListViewLoader()).execute(“http://10.0.2.2:8080/JSONServer/rest/ContactWS/get”);
}
[/java]
Edit: Some readers asked me how the Contact.java looks like. I add it here:
[java]public class Contact implements Serializable {private String name;
private String surname;
private String email;
private String phoneNum;
public Contact(String name, String surname, String email, String phoneNum) {
super();
this.name = name;
this.surname = surname;
this.email = email;
this.phoneNum = phoneNum;
}
// get and set methods
}
[/java]
line 39 in AsyncListViewLoader class is missing. Please include it before the line 1 in parsing JSON.
Do you mean the line String JSONResp = new String(baos.toByteArray());?
I have a question, where do you initialise the adapter object?
Sorry, I've added the piece of code missing. I will in a few hours make the source code available at github.
can you give a link at github?
Ok. i will do it. Sorry for the delay
Excuse me but can you show me you table of mysql with the data? please
If you mean the server side code, there isn't any db behind the server. Contacts name are created randomly.
Yes you can. The way you open an HTTP connection isn't important.
I found this website as an exceptional web tutorial because I am learning android programming in the last few days, and I am still very new in this case, both java and android programming. Can you make use of real examples, especially the connection between json, php, and mysql. On the other web is already a lot of tutorials like that, but in my opinion not good because of the tutorials I've read a lot of the error when I try, in this tutorial you created I really like because it is made in the form of objects that can be used repeatedly, but to me that is still beginner is still quite confusing because I need a real example in its use. I suggest you make a real example. Thank you all.
How does your Contact class look?
Does it have any constructor that takes the passed in parameters and sets them?
Google's Performance Tips for Android discourages the use of getter/setters.
http://developer.android.com/training/articles/perf-tips.html#GettersSetters
You declare the byte array b as size 1024. Is this safe?
What happens if the HTTP response is larger than 1024?
Google recommends to use HttpURLConnection over DefaultHttpClient.
As you should know this is a buffer not the full response length! The result is in ByteArrayOutputStream!!!!
So this is safe?
How do I know what a reasonable buffer size is?
You declared 1024, how should I know if I should use 1024, 2048, 4096, 8192, etc?
Hello,
Your tutorial was really useful. I appreciate the time and effort that devs like you spend writing this things.
My array response was too large, and I think the byte array was too small. I changed it for inputstreamreader and it worked fine.
http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/
Thanks again!!
🙂
The tutorial is great, but I don't understand how adpt che be accessible on the PostExecute of the async task…
You make both the adapter and AsynTask as private variable & class of the Fragment
private Adapter
private class AsyncTask
Thanks for the awesome tutorial!
thanks a lot!! very usrfull http://infomundo.org/android
I saw you insert your AsyncTask class in the Activity class. In my application my ListView is declared in a Fragment Class, not directly in the Activity, so how could I notify changes for the adapter ?
I saw you insert your AsyncTask class in the Activity class. In my application my ListView is declared in a Fragment Class, not directly in the Activity, so how could I notify changes for the adapter ?
I got this error:http://stackoverflow.com/questions/23441694/java-lang-illegalstateexception-system-services-not-available-to-activities-bef
Had to initialize adpt to null
@YehonatanTs:disqus your answer makes no sense
@YehonatanTs your answer makes no sense
VERYYYY HELPFUL THANKS A LOT!!!!
VERYYYY HELPFUL THANKS A LOT!!!!
Friend thank you very much your article helped me a lot, the only detail that is wrong with the code, the return is null in doinginBackGroun, but everything else is perfect …!
Friend thank you very much your article helped me a lot, the only detail that is wrong with the code, the return is null in doinginBackGroun, but everything else is perfect …!
Thank you Francesco! You just saved my project! Finally my list View is working after i understood the asyncTask more and implemented the adapter class on my own project(with different parameters definitely) in a proper way!
Thank you Francesco! You just saved my project! Finally my list View is working after i understood the asyncTask more and implemented the adapter class on my own project(with different parameters definitely) in a proper way!
Can I change the url to http://www.google.com or any other
I got error Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray. I have some confused about name of function of WebService which has been called. Please provide your webservice. I am working with asp.net
Thank you!!! Very good tutorial!
Hi, what would you chance if I had to shift data into a TEXTVIEW instead of a LISTVIEW?
can you show your json?