How to get all checked items from a ListView?

I’ve a couple of question I haven’t been able to figure out.

I’m trying to get all the checked elements from a ListView but:

  1. If I check and then uncheck an element, it’s returned as “checked” by the getCheckedItemPositions() function

  2. I don’t know how can I iterate through this:

    SparseBooleanArray checked = list.getCheckedItemPositions();
    

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The other answers using SparseBooleanArray are nearly correct, but they are missing one important thing: SparseBooleanArray.size() will sometimes only return the count of true values. A correct implementation that iterates over all the items of the list is:

SparseBooleanArray checked = list.getCheckedItemPositions();

for (int i = 0; i < list.getAdapter().getCount(); i++) {
    if (checked.get(i)) {
        // Do something
    }
}

Solution 2

I solved my case with this:

public class MyAdapter extends BaseAdapter{
    public HashMap<String,String> checked = new HashMap<String,String>();
....
    public void setCheckedItem(int item) {


        if (checked.containsKey(String.valueOf(item))){
            checked.remove(String.valueOf(item));
        }

        else {
            checked.put(String.valueOf(item), String.valueOf(item));
        }
    }
        public HashMap<String, String> getCheckedItems(){
        return checked;
    }
}

To set an element is checked:

public class FileBrowser extends Activity implements OnClickListener{        
private ListView list;

    ...
    list.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int item,
                long id) {

                        BrowserAdapter bla = (BrowserAdapter) parent.getAdapter();
                        bla.setCheckedItem(item);
                    }
    });

Then to get the checked items from outside the class..

MyAdapter bAdapter;    
Iterator<String> it = bAdapter.getCheckedItems().values().iterator();
                    for (int i=0;i<bAdapter.getCheckedItems().size();i++){
                        //Do whatever
                        bAdapter.getItem(Integer.parseInt(it.next());
                    }

Hope it can help someone.

Solution 3

Jarett’s answer is great, but this should be a bit faster, since it’s only checking the elements in the sparse array that are present in the underlying array (only those can be true):

SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
    final int checkedItemCount = checkedItemPositions.size();
    for (int i = 0; i < checkedItemCount; i++) {
        int key = checkedItemPositions.keyAt(i);
        if (checkedItemPositions.get(key)) {
            doSomething(key);
        } else {
            // item was in the sparse array, but not checked.
        }
    }

Pro tip: look at the source of SparseBooleanArray, it’s a pretty simple class:

http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/util/SparseBooleanArray.java/?v=source

Solution 4

My brain didn’t like looping through the SparseBooleanArray and I didn’t need a custom adapter, so the following was a little more intuitive for me:

  1. Don’t forget to use CHOICE_MODE_MULTIPLE in onCreate():

    getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

  2. Use the following method to get an ArrayList of them:

    // This example is to get an ArrayList of names (Strings)
    protected ArrayList<String> getNames() {
        ArrayList<String> names = new ArrayList<String>();
    
        for (int i = 0; i < getListView().getCount(); i++) {
            if (getListView().isItemChecked(i)) {
                // Do whatever you need to in here to get data from
                // the item at index i in the ListView
                names.add(mUsers.get(i).getName());
            }
        }
    
        return names;
    } 
    

Solution 5

You can iterate through the SparseBooleanArray using a for loop and the SparseBooleanArray’s size() and get(index) methods.

EDIT 3/2/2014: People have pointed out that SparseBooleanArray’s size() method returns the number of checked values, rather than the true length of the array, so I have mended my answer to account for that. Essentially it is the same, except that rather than iterating for the length of the array, we iterate until we have found all checked items. Since we only care about the number of checked items, it’s irrelevant that with this method, we may not actually get to the end of the array (we won’t see anything past the last checked item).

SparseBooleanArray checked = list.getCheckedItemPositions();

int numChecked = checked.size();

for (int i = 0; numChecked > 0; i++){
    if (checked.get(i)){
        //the item at index i is checked, do something
        numChecked--; //We found a checked item, so decrement the number of checked items remaining
    }
    else
        //the item is not checked, do something else
}

Solution 6

 final long[] checkedIds = lv.getCheckItemIds();
            for (int i = 0; i < checkedIds.length; i++) {
                Log.d("checkedIds", "id checked: " + checkedIds[i]);
            }

Solution 7

Just saw the question and I was facing the same problem.

There is a simpler solution using SparseBooleanArray to exactly count how many items are checked.
This is my onClick procedure:

@Override
public void onClick(View v) {
switch(v.getId()) {
  case R.id.button:
    SparseBooleanArray a = listView.getCheckedItemPositions();
    if(checked(vArray)>0) {
            String vCheckedList = "";
            for (int i = 0; i < nLength; i++) {
                if (a.valueAt(i) && i < nLength-1 && a.size()>1)
                    vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i))+"\n";
                else if (a.valueAt(i))
                    vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i));
            }
            Toast.makeText(getApplicationContext(), vCheckedList+ " is checked", Toast.LENGTH_SHORT).show(); 
            a.clear();
        } else
            Toast.makeText(getApplicationContext(), "No Item is Selected", Toast.LENGTH_SHORT).show();
        break;
    default:
        break;
        }
}

The checked method:

private int checked(SparseBooleanArray vArray) {
    int vCounter = 0;
    for(int i=0;i<vArray.size(); i++)
        if(vArray.valueAt(i))
            vCounter++;
    return vCounter;

}

It will solve both problem of the checked items.

Solution 8

I had the same problem and here is my solution with SparseBooleanArray :

SparseBooleanArray checkedPositions = lv.getCheckedItemPositions ();
int size = checkedPositions.size ();
for (int i=0 ; i<size ; i++) {
     // We get the key stored at the index 'i'
     int key = checkedPositions.keyAt (i);
     // We get the boolean value with the key
     Log.i (Tag, "checkedPositions(" + key + ")=" + checkedPositions.get (key));
}

Solution 9

In it’s entirety this is the solution I used.

Where pos is the Recyclerview item position

SparseBooleanArray selected = new SparseBooleanArray();

//OnClick listener here or whatever you use to check or uncheck an item
if (selected.get(pos, false)) {
        selected.delete(pos);
    } else {
        selected.put(pos, true);
    }

selected.size() will reveal how many items are selected

selected.get(pos) will return true if it’s selected

The following as has been stated, iterates over all those items which were selected:

for (int i = 0; i < list.getAdapter().getCount(); i++) {
    if (selected.get(pos)) {
        // Do stuff
    }
}

Solution 10

Here is how I get checked items from recyclerview adapter

fun getAllCheckedItems(outList){
         for (position in spareBooleanArray.keyIterator()) {
            outList.add(mList.get(position)
        }
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply