Android: Create ListView in XML and populate items using ArrayAdapter

3 September 2012 By Nithya Vasudevan 55,247 views One Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

Project Description

  • In the previous Android ListView example, we created ListView in XML and populated its items using android:entries attribute on list view element which points to the <string-array> defined by external resource in res/values/strings.xml.
  • In this example, we will show how to create ListView in XML layout and populate its items from string array defined by external resource (res/values/strings.xml) programatically using ArrayAdapter.
  • Job of an Adapter
    • defines how each row is displayed (i.e) the layout for each row). It can be a user defined layout defined in a XML file placed in res/layout or it can be default ListView layouts provided by Android system. (We will show these two methods in this example).
    • provides data to each row in ListView.
  • Here, we are going to implement OnItemClickListener event listener which calls onItemClick() callback method where we retrieve and display the item selected by the user.

Environment Used

  • JDK 6 (Java SE 6)
  • Eclipse Indigo IDE for Java EE Developers (3.7.1)
  • Android SDK 4.0.3 / 4.1 Jelly Bean
  • Android Development Tools (ADT) Plugin for Eclipse (ADT version 20.0.0)
  • Refer this link to setup the Android development environment

Prerequisites

Create Android Project

  • Create a new Android Project and name it as “ListViewDemo“.
  • Enter the package name as “com.theopentutorials.android“.
  • Enter the Activity name as “ListViewActivity2“.
  • Click Finish.

strings.xml

Open res/values/string.xml and replace it with following content.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, ListViewActivity2!</string>
    <string name="app_name">ListViewDemo</string>
     <string-array name="sports_array">
        <item>Shuttle Badminton</item>
        <item>Tennis</item>
        <item>FootBall</item>
        <item>Basket Ball</item>
        <item>Table Tennis</item>
        <item>Chess</item>
        <item>Hockey</item>
    </string-array>
</resources>

The <string-array> element defines the list of strings that will be displayed as list item in the ListView layout.

XML layout file

Open main.xml file in res/layout and copy the following content.

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

     <ListView
        android:id="@+id/sportsList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

In the XML layout file we have defined a ListView for displaying a scrollable list of items. These items can be of any type and for this example we have used string (TextView object) as each item.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.theopentutorials.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ListViewActivity1"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Method 1: Using row layout defined by Android system

Activity class

package com.theopentutorials.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListViewActivity2 extends Activity 
			implements OnItemClickListener {
    ListView listView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        listView = (ListView) findViewById(R.id.sportsList);
        
	String[] sports = getResources().getStringArray(R.array.sports_array);
        //Row layout defined by Android: android.R.layout.simple_list_item_1
        listView.setAdapter(new ArrayAdapter<String>(this, 
				android.R.layout.simple_list_item_1, sports)); 
        listView.setOnItemClickListener(this);  
    }
    
    @Override
    public void onItemClick(AdapterView<?> adapter, View view, 
				int position, long id) {
	Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
		  	          Toast.LENGTH_SHORT).show();
	}
}
  • To load the list view items, we first get the string array resource and used it in ArrayAdapter

Method 2: Using own row layout defined in XML file

Create a new XML row layout file and name it as “list_item.xml” in res/layout folder and copy the following content.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp" />

In the above Activity class, replace the listView.setAdapter() line with the following:

listView.setAdapter(new ArrayAdapter(this, R.layout.list_item, sports));

Output

Run your application

Project Folder Structure

The complete folder structure of this example is shown below.

Tags: , , , , , , , , , , , , , , ,

  • Marian Zsemlye

    As always, not fully maid help.
    If you enable filterig in list you wont be able to get real data.

    - you have a list with 30 posieiton
    - you filter them, so you get the last as the firs (and only one)
    - after clicking on it you get value from FIRST one !!!