Home » Android » Android Core » Android AsyncTask ListView – JSON

About Francesco Azzola

I'm a senior software engineer with more than 15 yrs old experience in JEE architecture. I'm SCEA certified (Sun Certified Enterprise Architect), SCWCD, SCJP. I'm an android enthusiast and i've worked for long time in the mobile development field.

Android AsyncTask ListView – JSON

Many times we need to populate a Listview using an 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 in 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, email and 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 webservices (in our case jersey api).

In this case, the app behaves like a client that invokes the remove service to get the contacts list and show it using the ListView. The data passed from the server to the client is formatted using JSON.

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:

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

}

By now everything is smooth and easy.

HTTP Client

One thing we need to do is creating our HTTP client in order to make 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 to do is creating an AsyncTask that makes this request and waits for the response.

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

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

}

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:

HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");

conn.connect();

next we create an input stream and then read the byte stream:

InputStream is = conn.getInputStream();
 // Read the stream
 byte[] b = new byte[1024];
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 while ( is.read(b) != -1)
    baos.write(b);

Now we have all the stream in our byte array and we need simply parse it using JSON.

JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
    result.add(convertContact(arr.getJSONObject(i)));
}

return result;

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:

super.onPostExecute(result);
dialog.dismiss();
adpt.setItemList(result);
adpt.notifyDataSetChanged();

 

Reference: Android AsyncTask ListView – JSON from our JCG partner Francesco Azzola at the Surviving w/ Android blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

4 comments

  1. Just the thing I was looking for.

    I was developing an Adroid App with a Async list view

  2. adpt istance where is declared?

  3. Can you share compelete source code of it

Leave a Reply

Your email address will not be published. Required fields are marked *

*


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.