Reputation: 505
This has been driving me insane. I have a ListView
and a ArrayList
as my adapter. The ListView
mode is CHOICE_MODE_MULTIPLE
and the layout is simple_list_item_checked
. I can now select multiple items in my ListView
.
My situation:
int length = jsonList.size();
SparseBooleanArray checked = lv_Devices.getCheckedItemPositions();
for (int i = 0; i <length ; i++ ){
if (checked.get(i)) {
onList.add(jsonList.get(i));
jsonList.remove(i);
lv_Devices.setItemChecked(i, false);
length--;
}
}
adapter.notifyDataSetChanged();
adapterOn.notifyDataSetChanged();
Here is the LogCat:
size of array 8 : contains [1, 2, 3, 4, 5, 6, 7, 8]
you removed index 0
[2, 3, 4, 5, 6, 7, 8]
you removed index 1
[2, 4, 5, 6, 7, 8]
you removed index 2
[2, 4, 6, 7, 8]
you removed index 3
[2, 4, 6, 8]
As you can see from the end result the array is shifting indexes. The goal I am trying to achieve: get each selected item and add them to the other ListView
while removing from the current ListView
.
The LogCat shows what happens when I select all the items. This is also happening on a button click. Any advice on this would be perfect. This is also my first time using stackoverflow. I don't really use it much as the majority of programming errors have been discussed on here. I am having difficulty on this subject.
Upvotes: 1
Views: 122
Reputation: 18281
Try something like this:
int item = 0;
for (int i = 0; i < length; i++) {
if (checked.get(i)) {
onList.add(jsonList.get(item));
jsonList.remove(item);
lv_Devices.setItemChecked(i, false);
}
else {
item++;
}
}
It will try to remove the first item in the array (item 0). If that item is checked, it will be removed. This means the item that was previously item 1 is now item 0, so it will just check item 0 again.
If, however, item 0 is not checked, it will move on to item 1, and keep doing the same thing.
Upvotes: 1