NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

Loading...
x

Wednesday, 7 April 2010

Simple ListView | Android Developer Tutorial (Part 16)

From exploring the various concepts related to fundamentals and to locations and maps, I would like to look at a few UI elements.


One of the simple views is a List View. In this post, I will explore a very simple list view using all the defaults provided by Android SDK and introduce you to a customized list view in the next blog article.

A List View, by name means being able to display a list of items in an order one below the other. For creating such a view, the first thing we have to do is extend the ‘ListActivity’ (android.app.ListActivity) instead of the normal Activity class.

So, here is how the class declaration should look:

public class MyListView extends ListActivity {
The ListActivity class provides a way of binding a source of data (an array or a cursor) to a ListView object through a ListAdapter.

In android, we all know that views are defined declaratively in XML files. It is the same here too. So, if we were to create our own custom ListView, we would have a declaration of this type:

<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000fff"
android:layout_weight="2"
android:drawSelectorOnTop="false">
</ListView>

However, if no ListView is declared, the ListActivity picks up a default ListView which fills the screen. So, in our example we will not declare any list view.

There is one more thing we need to define and that is how each row in the list should show up. This again, there are some defaults available which have names such as simple_list_item_1, simple_list_item_2, and two_line_list_item. So, in our example, I do not declare the layout for the rows but I will be using one of the defaults provided. So, in effect, I have not declared any layout – I am using the default screen layout and row layout.

Now, that we have the layouts out of our way, what else do we need for a List View. Of course, the list of data that needs to be displayed. Just to keep it simple, I will use an array of data for the same. So, here it is:

static final String[] PENS = new String[]{
"MONT Blanc",
"Gucci",
"Parker",
"Sailor",
"Porsche Design",
"Rotring",
"Sheaffer",
"Waterman"
};

Now, how do I bind this data to the default views described earlier? This is aided by a ListAdapter interface hosted by the ListActivity class that we have extended.

We need to use the setListAdapter(..) method of the ListActivity class to bid the two (data and view). Android provides many implementations of the ListAdapter. We will use the simple ArrayAdapter.

What does the ArrayAdapter expect?

It expects the context object, the row layout and the data in an array.

So here it is:

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, PENS));
With this we are done in creating the ListView.

I have added a small piece of code to show we can handle events on selecting an item in the list, by overriding the protected method shown below:

protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();
}

This toasts a message with the item selected.

The complete code is downloadable here.

31 comments:

  1. Thanks you,

    I started developing Java applications before the first public release of SUN JDK. Still, I often have difficulties understanding the Android API.

    It is great that blogs like yours exist, I only wish Google would hire you as head of documentation :)

    ReplyDelete
  2. oh wow this is great, can you please write a tutorial on how to get data from a database in the listview? with sql lite and or soap

    ReplyDelete
  3. Thanks for sharing your knowledge! this is exactly what I was looking for.

    ReplyDelete
  4. http://mfarhan133.wordpress.com/2010/10/14/list-view-tutorial-for-android/

    This a simple android list view tutorial, you can also apply onClick listener,, complete source code is available

    ReplyDelete
  5. No offense, but that's practically the same useless example Google put out.

    What we need is an example of how to get the actual data object associated with the listItem.

    ReplyDelete
  6. in this list view how can we catch the id of each list view item......plz tell me the procedure.......

    ReplyDelete
  7. I am Nasurudeen.MK(Flex developer) and i am new in android development. i need help from u. i need listview with pagination like android market and i got one sample from internet(EndlessAdapter Example), but i cant use that one in my project. here i attachment my code also. pls refer and help me to find the solution. its important..

    ReplyDelete
  8. Hai sai...I want help from u ...I want to uplaod the selected contact details like name,phone number,email from my emulator.But it shows improper results in the logcat..i.e;whenever i click on one item it shows some other conact in emulator...
    please help me out.Thanks in advance

    ReplyDelete
  9. Thanks so much for this post, Sai. It was super helpful!

    -Alvin

    ReplyDelete
  10. HI sai...
    I want a help from you.. Am the beginner of android.. I just want to get the selected item from the listview and it 'l be deleted as well as update too.. Could you please help me as soon as possible..
    Thanks in Advance..
    By Angel

    ReplyDelete
    Replies
    1. Use onListItemClick method

      Delete
  11. Hi saiGeetha garu,
    Your tutuorials were helpful to me a lot. i want a help from you.. in my application i want to paint some perticular area... but here is a problem, for this purpose i want a background image and select a frame foregroundly in that frame only i want to draw the paint.. can u provide code for it, how it will do programatically.. hope you help me..

    ReplyDelete
  12. I want to add onClick event to buttons which are present in listview,if i press button1 it has to perform some action1 and button2 perform action2,can u post code or else way to do.

    ReplyDelete
  13. hey really thanks for such a nice tutorial ......

    thanks a lot!!!!!!!!!!!

    ReplyDelete
  14. You just showed us how to toast a message once we click on list items in list view,But I need to start activity by clicking on List Items of List View,So please help me out.

    ReplyDelete
    Replies
    1. You should use an Intent. Just delete Toast code and instead put this:
      Intent i = new Intent (YourCurrentActivityNamemain,ClassNameYouWantToStart.class);
      startActivity(i);

      Delete
    2. Actually you need to have a "." before main:

      You should use an Intent. Just delete Toast code and instead put this:
      Intent i = new Intent (YourCurrentActivityName.main,ClassNameYouWantToStart.class);
      startActivity(i);

      Delete
  15. How can I create a listview that does not fill the whole screen, ie I also want a textview above the listview and buttons below it. And actually, I want to use an expandablelistview, not just a simple listview.

    Thanks a lot!

    ReplyDelete
    Replies
    1. Under the main layout you should have another layout which contains your listview. And in the main layout you can put whatever you want like buttons,textviews etc. After that it is a piece of cake:))

      Delete
  16. Hello Sai Geetha,
    I'm learning android programming by reading your blog, my problem is that I am not able execute setContentView() method, in a class extended by ListActivity. Please help me. I dont know how to go further. I made a new class extending with Activity, but of no use.

    ReplyDelete
  17. Chiru Nice Question i also want that Madam Plz help us...

    ReplyDelete
  18. Thanks a lot. You have simplified everything for us here.. Thanks a ton miss Sai Geetha. So nice of you.

    ReplyDelete
  19. hello,Geetha

    I'm Vinod I can't able to download the code..when i click on the link it shows an error msg that its invalid file or deleted..please help me..

    Really Excellent Tutorials helped me a lot.. :-)
    Thank You Very Much Geetha..

    ReplyDelete
  20. it's easy and nice tutorial which helpful to beginners.
    for more tutorial for android.visit:
    www.go2tricks.blogspot.com

    ReplyDelete
  21. A simple, concise example of generating a ListView in Android.

    Thanks much for having taken the time to put this out there for folks like me to see!

    ReplyDelete
  22. eh.. not so bad

    ReplyDelete
  23. Man your explanation is very simple, easy. Thanx, keep posting.

    ReplyDelete
  24. U said -"However, if no ListView is declared, the ListActivity picks up a default ListView which fills the screen. So, in our example we will not declare any list view." SO I didnt declare any listView in my main.xml layout file. Then it shows error -your content must have LisView whose id is "android.R.id.list"... After I added a ListView with the id - android:id="@android:id/list" ..It worked. Isnt it what U SAID or I got u wrong?

    ReplyDelete
  25. hi this is vela from chennai,i need one help from you,i fetch the data from server and stored vector..i need to create local DB for quick search,so how can i do that pls help me..sorry for my bad english....

    ReplyDelete
  26. Thanks, these simple tutorial helps. If anyone wants to learn How to make custom ListViews.

    ReplyDelete
  27. HI Geetha ,
    Am new to android
    what i want is listview with simplecursoradaper using Activity class not ListActivity

    ReplyDelete