How to create a ListView using ArrayAdapter in Android

Hello Android world :-) Today I am going to write a post about creating a ListView with the help of ArrayAdapter class. Lets directly move to the concept. Simply there are three things you have to concentrate;

  1. A data set
  2. A UI component to view the list
  3. A way to join the data set and the UI component

Before going to the coding I would like to explain the concept behind this. Because what I think is, if you know the concept, you can create your own code without copying others. So, look at the following figure. (click on the image if you cannot see it properly)

ListView using ArrayAdapter in Android
Figure 1

The three parts that I have mentioned in the first paragraph again plotted in to an image. It clearly shows what we are going to do in this blog post. In this example, our data set is going to be a String array which contains song names. I have hard coded it because I don’t want to complex this post at the initial level. For a complex scenario a data set can be an out put from a database or JSON (JavaScript Object Notation) file or a DTO (Data Transfer Object).

Then we need a UI (User Interface) component to view the data set. In this example I have used a ListView. UI components also have variations. As an example someone may need to show the data set in a GridView. Will see those options in later posts.

Then comes the main and the critical part. First I will tell the issue here. There is no way to plug a data set directly to the UI component like ListView. As you can see in the Figure 1, they have different kind of interfaces that is not matching. Therefore we need a third party support. That is an Adapter. Take a real world scenario. Sometimes your laptop charger cannot directly plug to the plug base in the wall. So you need an adapter that has an interface to the charger as well as to the wall base. Just like that, the ArrayAdapter class is act as the third party to complete our task in this example. Again, ArrayAdapter also not the only option. It is just one child of the Adapter family.

ListView using ArrayAdapter in Android
Figure 2

Enough explaining, otherwise you will get bored to read lengthy post :D Figure 2 shows the output of this example. Further explanations I have written as comments in the code. Here is what you are looking for,

package blog.anuja.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FirstActivity extends Activity {

	// Declare the UI components
	private ListView songsListView;

	// Declare an array to store data to fill the list
	private String[] songsArray ;

	// Declare an ArrayAdapter that we use to join the data set and the ListView
	// is the way of type safe, means you only can pass Strings to this array
	//Anyway ArrayAdapter supports only TextView
	private ArrayAdapter arrayAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Initialize the UI components
        songsListView = (ListView) findViewById(R.id.songsListView);

        // Initialize the songs array
        songsArray = new String[10];

        // Fill the songs array by using a for loop
        for(int i=0; i < songsArray.length; i++){
        	songsArray[i] = "Song " + i;
        }

        // For this moment, you have list of songs and a ListView where you can display a list.
        //But how can we put this data set to the list?
        //This is where you need an Adapter

        //context -  The current context. 
        //resource - The resource ID for a layout file containing a layout to use when instantiating views. 
        //textViewResourceId - The id of the TextView within the layout resource to be populated  
        //From the third parameter, you plugged the data set to adapter
        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, songsArray);

        // By using setAdapter method, you plugged the ListView with adapter
        songsListView.setAdapter(arrayAdapter);

        // Normally the argument of setAdapter ask for a ListAdapter instance.
        //And that is the best way of implementation of this code
        //We call it "programming to the interface"
    }
}

Above code display only the functions. If someone need the full example with the XML files which create the interfaces, go to my GitHub profile and download it.(click here)

Thanks for reading and feel free to ask any related question to this post. Enjoy :-)

About these ads

About anujarosha

An undergraduate in the stream of ICT (Information & Communication Technology). A simple person :)
This entry was posted in Android Examples. Bookmark the permalink.

34 Responses to How to create a ListView using ArrayAdapter in Android

  1. rohan says:

    Thanks for the post
    this is best post from all the post i have seen.
    again many many thnksssssss

  2. steve graham says:

    Thanks, but how do I solve the issue of opening an arrayAdapter class in a list view. See the issue below: http://stackoverflow.com/questions/8603541/how-to-inflate-setlistadapter-into-main-layout

  3. Siddharth says:

    it is the best post i have seen on listview thanks..

  4. amit sadh says:

    hi…anju …ur post is such a really very good and also vry helpful for beginner of android ……

  5. sravanthi says:

    Hi how can i navigate to another page by clicking on a item?

  6. seetha says:

    wow….really nice one….helpfull for newbies…it will be great if you give an example of using data set from resources?

  7. akky says:

    Hi Anu,
    Thanks for your nice tutorial. I have a question regarding this. If we have 7 images in the resource folder and 7 items in the list. How can we open an image by clicking an item in the list? Could you please write a tutorial on this?

    Thanks

  8. Lenin says:

    Where is the XML layout?

  9. Thanks for your post. It’s a very nice tutorial. If I had found this in the first place, it would have saved lots of time for me. Now I’m having issues with more complex things which are also related to ArrayAdapter. But again thanks so much for this.

  10. sandeep says:

    in above program what is “simple_list_item_1″

  11. Irshath says:

    Nice Post…

  12. sara ali says:

    it is superb post thanks.i have some questions related to android.in which platform i ask these

  13. จั่น says:

    thanks. very clear explanation

  14. Risny says:

    good post..:)

  15. what is difference between arrayadapter and listviewadapter can i use both to implement list

  16. Manish says:

    thanks..
    really a good post.

  17. Anil says:

    Nice Post…

  18. Sandeep says:

    Hey anuj…i have got a project which streams live video from your android camera phone to your laptop via bluetooth.can u help me with it???

  19. Rachita says:

    very informative post !! Thanks it helped me alot ! :)

  20. Jose Luis says:

    Thanks for the post, i had some problems with the setAdapter method, but not anymore.

  21. Ankit Baghel says:

    Great post…but i have a prblem understanding this line:” arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, songsArray);”

    what is the second argument for??
    where have u defined it??

  22. bharath says:

    Very nice tutorial

  23. Biswa Singha says:

    Best Article (*****) , there are lot’s of article i have read (last few weeks) most looks copy paste from other and little change.Hope you will come out with more article….

  24. Pranay says:

    finally got a nice explaination ..
    Thank you anujarosha..
    Could u tell me,how to implement using a DTO.

  25. Danilo Oliveira says:

    Thanks, i got it.

  26. Really great explanation…

  27. srinivas says:

    plzzz…. i need the code for listview for metro rail

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s