Reputation: 21
I have an alert dialog in which contains multiple list selection listener. Problem is that when i open first dialog after selection of multiple items i press positive button then on re open alert dialog it show nothing selected what i selected items when last opened.
final CharSequence[] dialogList= list.toArray(new CharSequence[list.size()]);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(SchoolFieldsData.this);
builderDialog.setTitle("Enter Average Fee");
int count = dialogList.length;
boolean[] is_checked = new boolean[count]; // set is_checked boolean false;
// Creating multiple selection by using setMutliChoiceItem method
builderDialog.setMultiChoiceItems(dialogList, is_checked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked) {
}
});
builderDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ListView list = ((AlertDialog) dialog).getListView();
// make selected item in the comma seprated string
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < list.getCount(); i++) {
boolean checked = list.isItemChecked(i);
if (checked) {
if (stringBuilder.length() > 0) stringBuilder.append(",");
stringBuilder.append(list.getItemAtPosition(i));
}
}
/*Check string builder is empty or not. If string builder is not empty.
It will display on the screen.
*/
if (stringBuilder.toString().trim().equals("")) {
// ((TextView) findViewById(R.id.text)).setText("Click here to open Dialog");
stringBuilder.setLength(0);
} else {
// ((TextView) findViewById(R.id.text)).setText(stringBuilder);
}
}
});
builderDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// ((TextView) findViewById(R.id.text)).setText("Click here to open Dialog");
}
});
AlertDialog alert = builderDialog.create();
alert.show();
Upvotes: 0
Views: 438
Reputation: 20278
This is because every time this code ins invoked a new AlertDialog is built (line 2) and new array of is_checked
is provided to it.
Try to restore the state, for example keep is_checked
array in different place and inside the positive button handler save the state to this array (instead of the line boolean checked = list.isItemChecked(i);
).
Upvotes: 1