check if there is at least a single true value in SparseBooleanArray

1.2k views Asked by At

I'm creating an Android app with a ListView and I'm using this line:

SparseBooleanArray checkedPositions = list.getCheckedItemPositions();

Then I want to iterate over the array but only if there is at least a single value which is true in the checkedPositions array.

Can something like this be done?

3

There are 3 answers

0
barunsthakur On

You cannot do that. But what you could do is to create another method which does that for you.

public boolean containsTrueValue(SparseBooleanArray sparseBooleanArray) {
    boolean containsBoolean = false;
    for (int i = 0; i < sparseBooleanArray.size(); i++) {
        if (sparseBooleanArray.valueAt(i) == true) {
            containsBoolean = true;
            break;
        }
    }
    return containsBoolean;
}
0
HexAndBugs On

ListView has a getCheckedItemCount(), so rather than checking your SparseBooleanArray you could work it out from your ListView. So, you could check:

list.getCheckedItemCount() > 0
1
Sebastian Pakieła On

ArrayList class in Java have method contains. You can cast your list to arrayList and use this method. Example:

ArrayList<Boolean> array = new ArrayList();

        array.add(false);
        array.add(false);
        array.add(false);
        array.add(true);
        array.add(false);
        array.add(false);

        boolean contains = array.contains(true);

contains variable will be true if you execute this code.