A simple Android ListActivity example

Android ListActivity FAQ: How do I create a class that extends the Android ListActivity class?

The easiest way to show a ListActivity example is to share some source code with the non-essential code stripped out. To that end, here's an example ListActivity class:

public class EntityListActivity 
extends ListActivity
{
  // your class fields here ...
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.entities_list);

    // set the list adapter
    String[] entities = {"Users", "Books", "Orders", "States"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, entities);
    setListAdapter(adapter);
    
    // other code in your class ...

Here's a quick summary of that code:

  • Your class extends ListView
  • In the onCreate method, you use setContentView to use the layout you defined in XML.
  • In this simple example, instead of getting the list data from a database, I created a simple Java String array.
  • I use the setListAdapter method of the ListActivity class to set my adapter.

Later on in this class, I use the following code to handle the event when a list element is selected. In this case, I get the text from the selected item, then show it in an Android Toast message:

public void onListItemClick(ListView parent, View v, int position, long id) {
  String item = (String) getListAdapter().getItem(position);
  Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();

  // alternatively, use 'position' with a string array defined in your class:
	//selection.setText(projectsAsStrings[position]);
}

There are several different ways to deal with the position you get when the onListItemClick method is called, and in this source code I've shared two of those approaches.

In summary, I hope this short example of how to extend the Android ListActivity class has been helpful.