I have a list which has multiple choice enabled and I needed to get the rows that are selected and will be passed to the previous activity. The getCheckedItemPositions() returned the number of "checkable" (true or false) rows not the rows that are selected. In my opinion, the name of that method is misleading. I'll be iterating the getCheckedItemPositions() to get the true ones and pass the number of selected rows to the previous activity. I'm wondering it might be something that is better than my solution?
Here are the previous code -
final SparseBooleanArray checkedItems = mListView.getCheckedItemPositions();
Team team;
final int checkedItemsCount = checkedItems.size();
int[] ids = new int [checkedItemsCount];
for (int i = 0; i < checkedItemsCount; ++i) {
team = new Team();
team = mListAdapter.getItem(checkedItems.keyAt(i));
list.add(team);
ids[i] = team.getTeamId();
}
Intent i = new Intent();
i.putExtra(INTENT_TEAM_SELECTION_SIZE, list.size());
i.putExtra(INTENT_TEAM_IDS, ids);
setResult(RESULT_OK, i);
finish();
My updated code -
final SparseBooleanArray checkedItems = mListView.getCheckedItemPositions();
Team team;
final int checkableItemsCount = checkedItems.size();
int selectedItemsCount = 0;
//get the count of selected rows
for (int i = 0; i < checkableItemsCount; ++i) {
if (checkedItems.valueAt(i)) {
selectedItemsCount++;
}
}
//Initialize the array of ids by the number of selected rows
int[] ids = new int[selectedItemsCount];
int index = 0;
for (int i = 0; i < checkableItemsCount; ++i) {
if (checkedItems.valueAt(i)) {
team = new Team();
team = mListAdapter.getItem(checkedItems.keyAt(i));
ids[index] = team.getTeamId();
index++;
}
}
Intent i = new Intent();
i.putExtra(INTENT_TEAM_SELECTION_SIZE, selectedItemsCount);
i.putExtra(INTENT_TEAM_IDS, ids);
setResult(RESULT_OK, i);
finish();