Sunday, November 25, 2012

ListView with Objects

Let's say you have just parsed some JSON data and you want to display them to a ListView.
For Simplicity sake I will assign all the properties of each item to only one TextView so we won't need to create a custom ArrayAdapter.

Assume that's our JSON data :

[  {"id":"1","title":"Homeland"},{"id":"2","title":"Breaking Bad"}{"id":"3","title":"Dexter"},{"id":"4","title":"Californication"}  ]

There's a JSON Array and that's everything in between [, ] and there are four  JSON Objects all of them with id and title properties.

First of all we are gonna create a class for our Objects :

public class TvShow() {
int id;
String title;
     public TvShow( int id, String title) { = id;
    this.title = title;
     public int getID() {
    return id;
        public String getTitle() {
    return title;
    public String toString(){
String toReturn = "ID = "+id + " Title= " +title ;
    return  toReturn;
Note that we need to Override the toString method for the Object TvShow so that every TextView in the list will display strings.

Initialize an ArrayList of  <TvShow> Obejcts :

     ArrayList<TvShow> alist = new ArrayList<TvShow>();

 So finally we store our data to a JSONArray object :

   JSONArray jArray = new JSONArray(result); //result is the String response we got from our web service

and get the length of the array. int len = jArray.length();

All we need to do now is a for statement to run the array for each item.

   for (int i = 0; i < len; i++) {
JSONObject jObj = jArray.getJSONObject(i);
            int _id = jObj.getInt("id");
String _title = jObj.getString("title");
                            JSONData jData = new JSONData(_id, _title);
   } catch (Exception e) {
// TODO: handle exception
return alist;

Now we have our ArrayList alist with TvShow Object's data.

            ArrayList<TvShow> results = GetResults(); //assuming the GetResults returns the alist from above

In our XML file we create a ListView and grab its id to the ListView item :

        ListView lv= (ListView)findViewById( );

Next we need to define our Adapter :
            ArrayAdapter<TvShow> arrayAdapter = new ArrayAdapter<TvShow>(this, android.R.layout.simple_list_item_1 , results );
The constructor is : 

public ArrayAdapter (Context context, int textViewResourceId, T[] objects)

The last thing we need to do is to assign the adapter to the ListView :

Now our ListView assings to an Object for every TextView item in the list.

No comments:

Post a Comment