Add a Simple List to an App

Lists are a basic building block of software. When writing applications getting a user to select an item from several options is a requirement that often occurs. Hence many frameworks have built in support for lists to make the programmer’s life easy, the Android SDK included. There is a View that can support a straightforward scrollable list of items, unsurprisingly called ListView. To support the ListView Android provides an extension to Activity, and yes it is called ListActivity. This tutorial shows how easy it is to add a list to an App using ListActivity. The example here will display a list of coffee types from which a user can select. It is easy to swap the list for anything required in your particular App.

In Eclipse open the App that needs a list selection screen. (Alternatively create a new project using the File menu, select New then Android Project. Fill in the Project Name, here MyAndroid is used. Click Next and select the build target from the installed APIs, any of the installed APIs will work, it can be changed later if required. Click Next and enter the Package Name in the required format, e.g. com.example, leave Create Activity checked and enter Main as the Activity name, click Finish.) The contents of the list are stored in a string array which can defined in a values file. With the res/values directory highlighted in the Eclipse Package Explorer use the File menu, select New then Android XML File. In the File box enter coffeelist.xml and click Finish. With coffelist.xml open select the XML view in the editior (using the tabs at the bottom of the edit dialog). Replace the contents with the following code to generate the source of the list for the program (see Copying Code from the Articles for tips).

[code lang=”xml”]<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="coffeeMenu">
<item>Filter</item>
<item>Americano</item>
<item>Latte</item>
<item>Espresso</item>
<item>Cappucino</item>
<item>Mocha</item>
<item>Skinny Latte</item>
<item>Espresso Corretto</item>
</string-array>
</resources>[/code]

Add a new class to the App (with the package highlighted under the src folder select New from the File menu then Class), here the new class is called CoffeeList, the class extends ListActivity. The class overrides OnCreate() as normal and there it can load the items for the list, replace the CoffeeList class in CoffeeList.java with this code:

[code lang=”Java”]public class CoffeeList extends ListActivity{
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
//Get the items for the list
String[] coffeeChoices = this.getResources().getStringArray(R.array.coffeeMenu);
}
}[/code]

Notice the use of R.array combined with the name of the array (coffeeMenu) in the XML file in the call to getStringArray(…). This is referencing the string array in the generated R class and is used to load the program array called coffeeChoices. With the data loaded the ListView to display it is needed. This is a simple list and Android has predefined ListViews for such lists, these Views are in the Android resources android.R.layout with names such as simple_list_item_1, simple_list_item_2, simple_list_item_single_choice and others. See the full list in the documentation at http://developer.android.com/reference/android/R.layout.html. Here simple_list_item_1 is used as the ListView.

With the data loaded into coffeeChoices, and the View available via Androids simple_list_item_1 a controller is needed to load the data into the View. To do that Android uses an Adapter class, which takes each item of data and creates the View to display it (and for simple_list_item_1 each entry in the ListView will be a TextView). The list here is stored in an array and thus here an Adapter subclass called ArrayAdapter is used. (For different data sources and other built in ListViews different Adapters would be required, see the documentation). The ArrayAdapter is instantiated with a reference to the Activity, the ListView (simple_list_item_1) and the data items (coffeeChoices). The ArrayAdapter is connected to the ListActivity using the setListAdapter() method. This code goes into the bottom of the onCreate() in the CoffeeList class.

[code lang=”Java”]ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, coffeeChoices);
setListAdapter(adapter);  //Provided by the ListActivity extension[/code]

In the Activity calling the list add a Button and code to start the ListActivity (CoffeeList), some code is also needed to handle the return from the ListActivity. Add the following code to the bottom of the res/layout/main.xml file just before the last LinearLayout tag if using the newly created project:

[code lang=”xml”]<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnCoffee"
android:text="Choose Coffee"/>[/code]

Code is added to attached an OnClickListener to the button and display the selected item in a Toast message, replace the Main class in Main.java with the following (imports for OnClickListener, View, Intent and Toast will be required):

[code lang=”Java”]public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btnCoffee).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Main.this, CoffeeList.class);
startActivityForResult(intent, 0);
}});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data != null && data.hasExtra("Order"))
Toast.makeText(this, data.getStringExtra("Order") + " ordered.", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Nothing ordered!", Toast.LENGTH_LONG).show();
}
}[/code]

Finally override the onListItemClick method in the CoffeeList class, when called if provides access to the ListView, the View clicked, its position in the list and the clicked View’s row id. These are used to access the clicked data, which is then sent back to the calling Activity, copy this code before the final brace (imports for the CoffeeList class will be ListActivity, Bundle, ArrayAdapter, ListView, View and Intent):

[code lang=”Java”]@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Intent data = new Intent();
data.putExtra("Order",item);
setResult(RESULT_OK, data);
finish();
}[/code]

Do not forget the AndroidManifest.xml entry for the ListActivity, add this before the closing </application> tag:

[code lang=”xml”]<activity android:name=".CoffeeList" android:label="Coffee Menu"/>[/code]

Run the App, when the button is pressed the list of coffee types is shown and the selected one is displayed back in the calling Activity:

Android List in Use

Not happy with the look of the list items provided in the Android ListView, roll your own. In the layout directory save a layout XML file with a TextView with the required format, for example this file is saved into listrow.xml:

[code lang=”xml”]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="@+id/tvListItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold|italic"/>
</LinearLayout>[/code]

Then the parameters to ArrayAdapter constructor are updated, telling Android to use a basic ListView but each row must follow the listrow.xml layout (each list row is effectively an instance of the layout’s TextView who’s id has been passed to the Adapter so that it knows to use it):

[code lang=”Java”]ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listrow, R.id.tvListItem, coffeeChoices);[/code]

A Basic Android List Customised

In summary, these are the steps to add selection from a list to an App:

  1. Create the data items for the list (e.g. a string array in a resource file or code).
  2. Create an Activity that extends ListActivity (remember to declare it in the manifest).
  3. Use an Android built in View for the list items or create one in the layout folder.
  4. Create an Adapter to link 1, 2 and 3. (e.g. an ArrayAdapter).
  5. Pass 1, 2, and 3 to an instance of the Adapter.
  6. Override onListItemClick() to get the selected item.
  7. Start the ListActivity and handle the return result.

Download some code that covers this article ready for importing into an Android project. The code can also be accessed via the Android Example Projects page. See the article Move Android Code Between PCs Running Eclipse on how to import example code into an Eclipse project. A version of this article was produced for the Android Cookbook.

One thought on “Add a Simple List to an App

Leave a Reply

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

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.