Android: Multiple Selection ListView

4 September 2012 By Nithya Vasudevan 55,334 views 10 Comments
32 Flares Twitter 5 Facebook 16 Google+ 11 32 Flares ×

Project Description

  • In the previous Android ListView examples, we created ListView with single selection mode.
  • In this example, we will create a ListView with multiple selection mode with button click event. On button click event, we retrieve the selected list view items and create a Bundle with array of selected items and store it in Intent and start another activity (ResultActivity).
  • ResultActivity retrieves the array and displays the result in ListView.

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 “ListViewMultipleSelection“.
  • Enter the package name as “com.theopentutorials.android“.
  • Enter the Activity name as “ListViewMultipleSelectionActivity“.
  • 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, ListViewMultipleSelectionActivity!</string>
    <string name="app_name">ListViewMultipleSelection</string>
    <string name="result_activity">ResultActivity</string>
    <string name="submit">Submit</string>
    
    <string-array name="sports_array">
        <item>Shuttle Badminton</item>
        <item>Tennis</item>
        <item>Table Tennis</item>
        <item>Basket Ball</item>
        <item>Foot Ball</item>
        <item>Volley Ball</item>
        <item>Hockey</item>        
        <item>Swimming</item>
    </string-array>
</resources>

XML layout files

This application uses two layout files,

res/layout/main.xmlRepresents first screen used by ListViewMultipleSelectionActivity.java
res/layout/result.xmlRepresents second screen used by ResultActivity.java

main.xml

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

    <Button
        android:id="@+id/testbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/submit" />

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/testbutton"
        android:layout_alignParentTop="true" 
        />		
</RelativeLayout>

result.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/outputList"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

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=".ListViewMultipleSelectionActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ResultActivity"
            android:label="@string/result_activity" >
        </activity>        
    </application>

</manifest>

Activity classes

ListViewMultipleSelectionActivity.java

package com.theopentutorials.android;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class ListViewMultipleSelectionActivity extends Activity implements
		OnClickListener {
	Button button;
	ListView listView;
	ArrayAdapter<String> adapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		findViewsById();

		String[] sports = getResources().getStringArray(R.array.sports_array);
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_multiple_choice, sports);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		listView.setAdapter(adapter);

		button.setOnClickListener(this);
	}

	private void findViewsById() {
		listView = (ListView) findViewById(R.id.list);
		button = (Button) findViewById(R.id.testbutton);
	}

	public void onClick(View v) {
		SparseBooleanArray checked = listView.getCheckedItemPositions();
		ArrayList<String> selectedItems = new ArrayList<String>();
		for (int i = 0; i < checked.size(); i++) {
			// Item position in adapter
			int position = checked.keyAt(i);
			// Add sport if it is checked i.e.) == TRUE!
			if (checked.valueAt(i))
				selectedItems.add(adapter.getItem(position));
		}

		String[] outputStrArr = new String[selectedItems.size()];

		for (int i = 0; i < selectedItems.size(); i++) {
			outputStrArr[i] = selectedItems.get(i);
		}

		Intent intent = new Intent(getApplicationContext(),
				ResultActivity.class);

		// Create a bundle object
		Bundle b = new Bundle();
		b.putStringArray("selectedItems", outputStrArr);

		// Add the bundle to the intent.
		intent.putExtras(b);

		// start the ResultActivity
		startActivity(intent);
	}
}
  • To load the list view items, we first get the string array resource and used it in ArrayAdapter. We use the list view row layout provided by the Android system (android.R.layout.simple_list_item_multiple_choice) and setting the selection mode as multiple using ListView.CHOICE_MODE_MULTIPLE.
  • We invoke getCheckedItemPositions() on list view object which returns the set of checked items (as SparseBooleanArray) in the list

ResultActivity.java

package com.theopentutorials.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ResultActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.result);

		Bundle b = getIntent().getExtras();
		String[] resultArr = b.getStringArray("selectedItems");
		ListView lv = (ListView) findViewById(R.id.outputList);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, resultArr);
		lv.setAdapter(adapter);
	}
}

Output

Run your application
First Screen

Second Screen

Project Folder Structure

The complete folder structure of this example is shown below.

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

  • krunal

    please give me download link of code ….or mail me…

  • sathish

    hi Nithya,
    I am havaing a doubt in your project. Plz, let me know how can i save the checked state of the list view true after coming from another activities???

  • omi

    Its not working for json data.Please help me to do it.

    • Huy

      @omi: yep, it will not work for JSON Object. Just parse JSON OBject to Array object or List and it will work.
      Cheers,
      Huy

  • omi

    i want to do same thing for json data but its not working. it gives me error that hashmap value cannot convert to string.

  • gen

    it would be great if there’s a source code for this.

  • shyam

    Hi,

    The above code is not clearing the previously selected items. Please help me how to pass only selected items to the next screen.

  • royalopez06

    Very nice tutorials, but how can I use this with sqlite, can you please help me with this, many thanks…

  • Ricardo Silveira

    hi Nithya,

    How can I use dynamic MultiSelector? ie, returning results database for MultiSelector?

    thank you

  • Ivan Rodrigues

    Excelent post. Congratulations !!! You’re in the right way !!!