SparseBooleanArray side effects?

80 views Asked by At

I have a ListView in which I could select multiple items.

Then, I scan for which ones were actually selected.

The following code doesn't bug out on me.

SparseBooleanArray checkedNetworks = networksList.getCheckedItemPositions();

if (checkedNetworks != null) {
    int len = checkedNetworks.size();

    Log.v("checkedNetworks", checkedNetworks.toString());

    for (int i = 0; i < len; i++) {
            int key = checkedNetworks.keyAt(i);
            Log.v("network:", networks.get(key).getName());
            selectedNetworkIds.add(networks.get(key).getId());
    }
}

That could works. Beautifully, in fact. The problem is that I'm not checking to see if a Network in the ListView was actually selected. This is important, because while the User may have at one point selected the Network (being the reason for it being in the SparseBooleanArray), they could have deselected it, in which case the value would be false in the SparseBooleanArray.

So I tried this.

SparseBooleanArray checkedNetworks = networksList.getCheckedItemPositions();

    if (checkedNetworks != null) {
        int len = checkedNetworks.size();

        Log.v("checkedNetworks", checkedNetworks.toString());

        for (int i = 0; i < len; i++) {
            if (checkedNetworks.valueAt(i)) {
                int key = checkedNetworks.keyAt(i);
                Log.v("network:", networks.get(key).getName());
                selectedNetworkIds.add(networks.get(key).getId());
            }        
        }
    }
}

Now, I get a NullPointer Exception at checkedNetworks.keyAt(i). This implies that we got through the if-statement clause and then something derped. I have no idea why this is happening.

FATAL EXCEPTION: Thread-44215
at java.lang.NullPointerException at line 89.
at java.lang.Thread.run

That is the only relevant information in the stack trace.

0

There are 0 answers