I have my multiple selection dialog running and popping up with the right values. However I’m struggling to understand how to set and retrieve the values when the save button is clicked.
My code is the following:
public void addCondition(View view){
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
Cursor f = db.rawQuery("select * from assetobservationtypes", null);
Log.e("Asset Helper Types:", "Cursor run");
List<CharSequence> mHelperNames = new ArrayList<CharSequence>();
final ArrayList<String> mHelperNamesID= new ArrayList<String>();
if(f.getCount() > 0) {
f.moveToFirst();
while(!f.isAfterLast()) {
mHelperNames.add(f.getString(f.getColumnIndex("Observation")));
mHelperNamesID.add(f.getString(f.getColumnIndex("AssetObsID")));
f.moveToNext();
}
}
f.close();
final List<Integer> mSelectedItems = new ArrayList<Integer>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title")
.setMultiChoiceItems(mHelperNames.toArray(new CharSequence[mHelperNames.size()]), null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer
.valueOf(which));
}
}
})
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
txtCondition.setText("set");
txtCondition.setTextColor(Color.parseColor("#4c9226"));
count++;
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.show();
}
I understand the list is in the array mSelectedItems, however when i tried to do a log of mSelectedItems.get(0) on the onclick of setPositiveButton to test it held anything the app just crashed.
How do I retrieve / store these values? And then pre-populate the list next time
Tom
I guess that by pre populating the list next time you want to show the checked items in the
AlertDialogwhen the dialog is showed again. In this case make themSelectedItemsa field in yourActivity(will initially be an empty list):and your calling method:
Keep in mind that the
mHelperNameslist should be the same(you can’t change values in theCursor)otherwise you risk in having some inconsistency between checked/unchecked items or even exceptions. I hope the code is right, I didn’t tested it.