Tek Eye Logo

Tek Eye

Two Line Lists In Android

In the tutorial Add a Simple List to an App example code was given to show how to load a ListView from a string array. This article shows how each list item in a ListView can display two lines of data, in this case each list item will be an American state and its capital. The two line list example in this tutorial also applies to a ListActivity which is simply an Activity with a built in ListView.

Android Logo

(This Android Two Line List tutorial assumes that Android Studio is installed, a basic App can be created and run, and the code in this article can be correctly copied into Android Studio. The example code can be changed to meet your own requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter.)

A SimpleAdapter Loads a ListView with Two Line Entries

A common pattern in Android is to define a View in XML, set up the data that will be displayed in the View, then provide the code to load that data into the View. In the case of a ListView (or ListActivity) the work is done by an Adapter. For a list with single line entries an ArrayAdapter does the job, as seen in the Add a Simple List to an App example. Adding another line of data for each entry in the list requires the SimpleAdapter.

The code in this tutorial will define a two dimensional string array to hold the American States names and capitals data. Normally such arrays are read from a database or a web service. Two TextViews in a layout define the template for each two line list entry. The work of inflating the Views for each list entry and setting the values in the Views is done by a SimpleAdapter. An ArrayList and HashMap ensures the data goes into the correct TextView for each list entry. This diagram summarises what the code achieves.

ListActivity and SimpleAdapter for Two Lines of Strings

For this tutorial a new project was started in Android Studio called State Capitals using an Empty Activity, all other entries for the Create New Project wizard being left at their default values.

Define the Data

Under the java folder in the Project explorer tree open the MainActivity.java file (or whatever your named it). At the bottom of the class, just before the last closing brace (curly bracket), add a two dimensional string array to define our data. Here only a few values are shown, all fifty states are in the downloadable project code.

private String[][] StatesAndCapitals =
    {{"Alabama","Montgomery"},
    {"Alaska","Juneau"},
    {"Arizona","Phoenix"},
    {"Arkansas","Little Rock"},
    {"California","Sacramento"},
    {"Colorado","Denver"},
    {"Connecticut","Hartford"},
    {"Delaware","Dover"},
    {"Florida","Tallahassee"},
    {"Georgia","Atlanta"},
    {"Hawaii","Honolulu"},
    {"Idaho","Boise"},
    {"Illinois","Springfield"},
    {"Indiana","Indianapolis"},
    {"Iowa","Des Moines"},
    {"Kansas","Topeka"},
    {"Kentucky","Frankfort"},
    {"Louisiana","Baton Rouge"},
    {"Maine","Augusta"}};

Define the Views for Each List Entry

Each of the two lines in the list entry will be a TextView, and since a layout file needs a single root they are wrapped in a simple LinearLayout. Select the res/layout folder in the Project explorer and use the context menu (usually right-click) or File menu select New then XML and Layout XML File. Give the layout file a name, here twolines is used. The root tag is LinearLayout. With twolines.xml open in Design mode click on the screen then set orientation in the Properties list to vertical. Drop two TextViews from the Palette onto the two lines layout. The top TextView ID is changed to line_a and the bottom to line_b. Style the TextViews as required, here the top is made italic, white and size 16sp, the bottom a bright green. The two lines layout XML should resemble the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/line_a"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="#FFFFFF"
        android:textSize="16sp"
        android:textStyle="italic" />

    <TextView
        android:id="@+id/line_b"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="#BFFF00"
        android:textSize="14sp" />
</LinearLayout>

Load an ArrayList with the Data and Keys via HashMaps

Each entry in the ArrayList is a HashMap, the HashMap links the data to each line in the list entry via a Key. The declaration of the ArrayList at the top of the Java class is:

ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();

Imports for ArrayList and HashMap are required. After the call to setContentView the string array is looped through and a HashMap created for each pair. The keys line1 and line2 are used. Each HashMap is added to the ArrayList:

HashMap<String,String> item;
for(int i=0;i<StatesAndCapitals.length;i++){
    item = new HashMap<String,String>();
    item.put( "line1", StatesAndCapitals[i][0]);
    item.put( "line2", StatesAndCapitals[i][1]);
    list.add( item );
}

Create the SimpleAdapter

At the top of the class declare the SimpleAdapter (the import for SimpleAdapter will need to be added):

private SimpleAdapter sa;

It is configured after the code that loads the list:

sa = new SimpleAdapter(this, list,
        R.layout.twolines,
        new String[] { "line1","line2" },
        new int[] {R.id.line_a, R.id.line_b});

Notice that the keys line1 and line2 are passed in as well as the View ids line_a and line_b. Linking the data to the Views.

Add the ListView to Display the Data

Next a ListActivity or an Activity with a ListView is required. Here the default layout (called activity_main.xml) is opened and the Hello World TextView deleted. From the Containers on the Palette a ListView is dropped on to the screen. The ListView is given an ID of list and layout_width and layout_height is set to match_parent. Here is res/layout/activity_main.xml with a ListView added:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.statecapitals.MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Link the Adapter to the List

The call to setAdapter completes the code before the closing brace for onCreate (the import for ListActivity will be required):

((ListView)findViewById(R.id.list)).setAdapter(sa);

(If using a ListActivity it is simply setListAdapter(sa); instead.)

Two Line List Example

An example project is provided in two_line_listactivity.zip for importing into Android Studio. It is also available from the Android Example Projects page.

Full Class Code

Here is the full Java class listing with imports:

package com.example.statecapitals;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
    private SimpleAdapter sa;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HashMap<String,String> item;
        for(int i=0;i<StatesAndCapitals.length;i++){
            item = new HashMap<String,String>();
            item.put( "line1", StatesAndCapitals[i][0]);
            item.put( "line2", StatesAndCapitals[i][1]);
            list.add( item );
        }
        sa = new SimpleAdapter(this, list,
                R.layout.twolines,
                new String[] { "line1","line2" },
                new int[] {R.id.line_a, R.id.line_b});
        ((ListView)findViewById(R.id.list)).setAdapter(sa);
    }

    private String[][] StatesAndCapitals =
        {{"Alabama","Montgomery"},
        {"Alaska","Juneau"},
        {"Arizona","Phoenix"},
        {"Arkansas","Little Rock"},
        {"California","Sacramento"},
        {"Colorado","Denver"},
        {"Connecticut","Hartford"},
        {"Delaware","Dover"},
        {"Florida","Tallahassee"},
        {"Georgia","Atlanta"},
        {"Hawaii","Honolulu"},
        {"Idaho","Boise"},
        {"Illinois","Springfield"},
        {"Indiana","Indianapolis"},
        {"Iowa","Des Moines"},
        {"Kansas","Topeka"},
        {"Kentucky","Frankfort"},
        {"Louisiana","Baton Rouge"},
        {"Maine","Augusta"}};
}

See Also

Archived Comments

SavTheCoder on May 29, 2012 at 5:14 pm said: Thank you for this tutorial. It’s good to finally get the painful process of adding two-lined lists, thanks to your help. Thanks again -Sav

Ron on July 13, 2012 at 10:20 pm said: Very nice example, clear, clean, simple and more importantly, it works! It helped me out a lot. KUDOS!

Marcel on December 9, 2012 at 4:49 pm said: Clear and simple tutorial, thank you!

I have just one comment to your code, when defining ArrayList and HashMap, you are breaking encapsulation. You should use it like this:

List<Map> list = new ArrayList<Map>();
Map item = new HashMap();

Tek Eye on December 9, 2012 at 11:30 pm said: Thank you. The declarations used are clear for less experienced programmers, particularly when calling the SimpleAdapter constructor, of course everyone can adapt the code to their preferred style.

Refka on April 10, 2013 at 7:30 pm said: thank you but how to make it dynamic with json and php!!

Tek Eye on April 11, 2013 at 8:34 am said: Use json_encode in PHP to generate the string array as a json object on the website. Use URL to make a HTTP request with HttpURLConnection to get the json object (INTERNET permission must be requested) from the App. Parse the received string directly or using the Java JSON classes to generate the string array for the two line list.

Ana Maria on April 11, 2013 at 3:45 pm said: I would like to thank you for writing this tutorial. I am a newbie on Android and need to create and Android app for my final year project. You solved a problem that I had for 1 day now. With your help I was able to make progress in my project. The best tutorial ever.

Anjith Sasindran on October 6, 2014 at 6:50 am said: Awesome tutorial man. Helped me a lot. All other tutorials are like creating a class which extends ArrayAdapter or BaseAdapter. This one is really good and simple to implement.

Tek Eye on October 6, 2014 at 9:20 am said: Thank you for the comment. Enjoy your Android programming.

pratik on December 8, 2014 at 11:08 am said: How to add onclicklistener in this list?

Ankit Agrawal on February 17, 2015 at 11:02 am said: GREAT JOB!! Thanks.

Mick on September 23, 2015 at 9:15 pm said: Thank you. Have looked all over for a simple example of this. Now I see just how simple it can be, and I am confident I can get it to work in my App.

Author:  Published:  Updated:  

ShareSubmit to TwitterSubmit to FacebookSubmit to Google+Submit to LinkedInSubmit to redditPrint Page

markdown CMS Small Logo Icon ↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.



Articles on:

Android, HTML, VPS, Computing, IT, Computer History, ↓markdown↓ CMS



Free Android Projects and Samples:

Android Examples, Android List Examples, Android UI Examples