2014-10-13 3 views
1

Я могу сохранить выбор, пока я использую приложение, но всякий раз, когда я закрываю приложение и перезапускаю его, выбор снова пуст. Где я иду не так? Он всегда загружает значение по умолчанию «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(); 
    } 

ответ

1

В начале (строка 4), вы пытаетесь загрузить переменную с именем "currentChoice":

final int[] currentChoice = {choiceSettings.getInt("currentChoice", 0)}; 

В общем, вы сохраните переменную с editor.putInt(String key, int value). Таким образом, key - это имя, используемое для сохранения вашей переменной.

Когда вы пишете

currentChoice[0] = 0; 
editor.putInt(String.valueOf(currentChoice[0]), 0); 

String.valueOf(currentChoice[0]) становится "0". Вы сохраняете int 0 для переменной с именем «0». Так, вторая строка в

editor.putInt("currentChoice", currentChoice[0]); 
+0

Это работает безупречно. Спасибо за объяснение. –

1

Вы используете два контейнера общих предпочтений - стандартный и настраиваемый. Используйте только по умолчанию.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 
final SharedPreferences.Editor editor = preferences.edit(); 
final int[] currentChoice = {preferences.getInt("currentChoice", 0)}; 
+0

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

+0

Не могли бы вы добавить трассировку стека к своему сообщению? – ToYonos

Смежные вопросы