0

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();
Meep
  • 501
  • 6
  • 24

1 Answers1

0

This solution looks a bit cleaner, perhaps check it out? :)

https://stackoverflow.com/a/8726923/1337802

Community
  • 1
  • 1
Blackchai
  • 41
  • 6
  • It looks cleaner. I have other messy operations to get it what I needed. I posted this topic since I googled this issue and didn't see what I needed. I guess I'll stick to my solution. – Meep Apr 23 '15 at 23:35