How to get Selected items from Multi Select List View

List View –

We can also populate a ListView in which we can select more than one data items.

So if you want to create a ListView in which you can select more than one Item. Then we have to pass any of these two options when creating the Object of ArrayAdapter.

android.R.layout.simple_list_item_multiple_choice
OR

android.R.layout.simple_list_item_checked

Syntax –


new ArrayAdapter(context, android.R.layout.simple_list_item_checked,String[] objects);

or

new ArrayAdapter(context, android.R.layout.simple_list_item_multiple_choice
,String[] objects);

If you use these two options at the time of Creation of ArrayAdapter object. Then ListView will be multi select in nature.

So our Next Task is to get all selected Item from this type of ListView.

If you want to get all the selected items from this list view then we can use

getCheckedItemPositions()
method list view. This method will return SparseBooleanArray object.and this object contains detail of all checked item of ListView.

So first take a Look of code sample …then I will discuss complete code step by step.

Code Sample –

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    
    <string name="app_name">ListViewCustomizedEx</string>
    <string-array name="freedomFighters">
    <item>Sardar Bhagat Singh</item>
    <item>Bal Gangadhar Tilak</item>
    <item>Chandra Shekhar Azad</item>
    <item>Khudi Ram Bose</item>
    <item>Subhash Chandra Bose</item>
    <item>Shiv Ram Rajguru</item>
</string-array>

</resources>


ListViewCustomizedExActivity.java

package com.ui.yogeshblogspot;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ListViewCustomizedExActivity extends ListActivity{
    /** Called when the activity is first created. */
	String[] freedomFighters;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListView lview=getListView();
       lview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);        
    lview.setTextFilterEnabled(true);
        freedomFighters=getResources().getStringArray(R.array.freedomFighters);
        setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice,freedomFighters));
            }
    public void onListItemClick(
    		ListView parent, View v, int position, long id)
    		{
    		//---toggle the check displayed next to the item---
    	    String s="";
    		int len =parent.getCount();
    		SparseBooleanArray checked=parent.getCheckedItemPositions();
    		for (int i = 0; i &lt; len; i++)
    			 if (checked.get(i)) {
    			  String item = freedomFighters[i];
    			  s=s+" "+item;
    			  /* do whatever you want with the checked item */
    			 }
    		Toast.makeText(this,"Selected Items- " + s,Toast.LENGTH_SHORT).show();
    		}

 }

In this application there is no use of main.xml file. Because in this code sample I am defining complete layout in java class.

But in this application I am using strings.xml file to store string resources. so take a look at string.xml file .

    
    <string-array name="freedomFighters">
    <item>Sardar Bhagat Singh</item>
    <item>Bal Gangadhar Tilak</item>
    <item>Chandra Shekhar Azad</item>
    <item>Khudi Ram Bose</item>
    <item>Subhash Chandra Bose</item>
    <item>Shiv Ram Rajguru</item>
</string-array>

In this code sample I am defining a string array resource with namefreedomFighters.and inside this string array I am storing some popular name of Indian freedom fighters using item tag.
I will use these data items to populate ListView.

Now let’s discuss the Activity Class step by step.

In this Activity class I am extending the android.app.ListActivity class to make this activity as ListActivity.
And inside the Activity class I am creating a Array reference variable of String type with name freedomFighters.

I will use this array to store all strings data from strings.xml file.

String[] freedomFighters;

Now let’s discuss the onCreate() method of this Activity class.
Inside the onCreate() method first I am getting the reference of listView by calling the getListView() method of ListActivity.

ListView lview=getListView();

Then because I want to select more than one item from list view then I am calling setChoiceMode() method with value ListView.CHOICE_MODE_MULTIPLE.

lview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

this code make this List View as Multi select.

Then I am calling setTextFilterEnabled() method with true as parameter.

lview.setTextFilterEnabled(true);

It is used for filtering the contents of the given ListView .when you type a letter then you will be automatically scrolled to that item if it is there in that view .

Then I am getting the string array resources from string.xml file and assigning the reference to freedomFighters array.

freedomFighters=getResources().getStringArray(R.array.freedomFighters);

and finally I am calling the setListAdapter() method and passing the object of ArrayAdapter.


setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice,freedomFighters));

the above line will populate the multi select ListView with freedomFighters data items.

Then I am defining the onListItemClick() method of ListActivity.then method automatically called when user click on any item of ListView.

public void onListItemClick(
    		ListView parent, View v, int position, long id)
    		{
    		//---toggle the check displayed next to the item---
    	    String s="";
    		int len =parent.getCount();
    		SparseBooleanArray checked=parent.getCheckedItemPositions();

    		for (int i = 0; i &lt; len; i++)
    		   {
    			 if (checked.get(i)) {
    			  String item = freedomFighters[i];
    			  s=s+" "+item;
    			  /* do whatever you want with the checked item */
    			 }
    		   }
    		Toast.makeText(this,"Selected Items- " + s,Toast.LENGTH_SHORT).show();
    		}

In this method I am getting total no of items of listview by getCount() method of ListView.
Then I am getting the position of All checked items of ListView by calling getCheckedItemPositions() method.this method returns SparseBooleanArray.

Object of SparseBooleanArray contains data items as key value pair.in this case this will contain index no of data items as key and selected state(true of false) as value.

So we can se that SparseBooleanArray is same as HashMap to map Integers to Booleans. But it is more efficient than HashMap.
Then I am iterating all the elements of sparse array and inside the loop I am checking the state of elements by calling get(key) method of SparseBooleanArray.
This method return true I value(true or false) of particular element. Then inside if condition I am composing result string.
And finally I am displaying result string using Toast message.

Output –
ListView























Code Sample – Click here to download ListViewCustomizedEx.rar

Leave a Reply