сохранить контрольный список MultipleChoices в AlertDialog

Я работаю с диалоговым окном предупреждений с множественным выбором. и я хочу сохранить выбранные значения, поэтому, когда пользователь возвращается к диалоговому окну предупреждений, значения, которые он выбрал ранее, все еще проверяются. Мой код:

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();
}

}

Есть ли способ сделать это с помощью общих настроек (сохранить массив)? так же, как этот ответ.

Спасибо.


person RidRoid    schedule 14.10.2014    source источник


Ответы (2)


Вы можете сохранить свои данные как ArrayList, используя SharedPreferences, как показано в этом ответе

person Artem Mostyaev    schedule 14.10.2014
comment
Я пытался следовать тому, что было в ответе... но все еще не могу заставить его работать... вот мой обновленный код: gist.github.com/RidouaneHicham/54c1cb3b2d326a917175 можете ли вы взглянуть и убедиться, что мой код в порядке? - person RidRoid; 16.10.2014
comment
Возможно, вам не нужно сохранять данные как набор, лучше сохранить логический массив, как показано во втором ответе на связанный вопрос. - person Artem Mostyaev; 16.10.2014

Задача решена. здесь ответ с решением и объяснением.

person RidRoid    schedule 02.11.2014