Я могу сохранить выбор, пока я использую приложение, но всякий раз, когда я закрываю приложение и перезапускаю его, выбор снова пуст. Где я иду не так? Он всегда загружает значение по умолчанию «0» вместо запоминания последнего выбора.Сохранить выбор переключателя в диалоговом окне предупреждения Android
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
SharedPreferences choiceSettings = getSharedPreferences("currentChoice", 0);
final int[] currentChoice = {choiceSettings.getInt("currentChoice", 0)};
final CharSequence[] items = {"AT&T", "Tmobile", "Verizon", "Sprint", "Other"};
// Decide which carrier, so we can apply the correct forwarding code.
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select your carrier");
builder.setIcon(R.drawable.ic_launcher);
builder.setSingleChoiceItems(items, currentChoice[0],
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
switch (item) {
case 0:
Toast.makeText(getApplicationContext(),
items[item], Toast.LENGTH_SHORT).show();
// Your code when first option seletced
currentChoice[0] = 0;
editor.putInt(String.valueOf(currentChoice[0]), 0);
editor.putString("fCode", "*67*");
editor.apply();
break;
case 1:
// Your code when 2nd option seletced
Toast.makeText(getApplicationContext(),
items[item], Toast.LENGTH_SHORT).show();
currentChoice[0] = 1;
editor.putInt(String.valueOf(currentChoice[0]), 0);
editor.putString("fCode", "*67*");
editor.apply();
break;
case 2:
// Your code when 2nd option seletced
Toast.makeText(getApplicationContext(),
items[item], Toast.LENGTH_SHORT).show();
currentChoice[0] = 2;
editor.putInt(String.valueOf(currentChoice[0]), 0);
editor.putString("fCode", "*67*");
editor.apply();
break;
}
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Это работает безупречно. Спасибо за объяснение. –