I'm working with an alertdialog with multiplechoices. and I want to store the selected values so when the user comes back to the alertdialog, the values he selected previously are still checked. My code :
public class TimelineSettings extends DialogFragment {
final ArrayList selected_categories = new ArrayList();
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor sharedPrefEditor;
final CharSequence[]items = {"Fourniture","Nourriture","Voyages","Habillement","Médias","Autres"};
boolean[] itemsChecked = new boolean[items.length];
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle("Choisissez vos paramètres")
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int indexselected,
boolean isChecked) {
itemsChecked[indexselected] = isChecked;
if (isChecked) {
// If the user checked the item, add it to the selected items
selected_categories.add(indexselected);
} else if (selected_categories.contains(indexselected)) {
// Else, if the item is already in the array, remove it
selected_categories.remove(Integer.valueOf(indexselected));
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
}
})
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
Is there a way to do it with sharedpreferences (store an arraylist) ? same as this answer.
thanks.