Esteban Esteban - 2 years ago 105
Java Question

Multichoice AlertDialog get selected values as Strings

I get a

List
from server which I show as fields in
MultiChoice AlertDialog
. When the user checks a field I place it in another
List
. But I only get them as integers. How can I know which one was checked because I need the name of the item?

List<Integer> mSelectedItems = new ArrayList<>();

@Override
public void renderGenreList(List<Genre> genreList) {
CharSequence[] genreChar = convertGenreList(genreList);
genreDialog(genreChar);
}

private CharSequence[] convertGenreList(List<Genre> genreList) {
List<String> genreString = new ArrayList<>();
for (int i = 0; i < genreList.size(); i++) {
Genre genre = genreList.get(i);
genreString.add(genre.getName());
}
return genreString.toArray(new CharSequence[genreString.size()]);
}

private void genreDialog(CharSequence[] genres) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder
.setTitle(R.string.multiple_choice_title)
.setMultiChoiceItems(genres, null, (dialog, which, isChecked) -> {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer.valueOf(which));
}
})
.setPositiveButton(R.string.OK_button, (dialog, which) -> {

dialog.dismiss();
})
.setNegativeButton(R.string.CANCEL_button, (dialog, which) -> dialog.dismiss());
d = builder.create();
}

Answer Source

Your mSelectedItems list has the list of selected items position. So you can do below to get all items

for (int i = 0; i < mSelectedItems.size(); i++) {
        Genre genre = genreList.get(mSelectedItems.get(i));
        // Here genre is one of the items selected and you can get all items in this loop
}

or second method is when you are adding values to mSelectedItems instead of adding which get the value and then add

replace -

mSelectedItems.add(which);

with

mSelectedItems.add(genreList.get(which));

then you will have mSelectedItems with list of selected items. Update the above for remove method as well.

the third way is to have instance of your dialog and get from there.

AlertDialog mAlert = builder.create();
// Display the alert dialog on interface
mAlert.show();

// get list of selected items
mAlert.getListView().getCheckedItemPositions();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download