我可以在使用应用程序时保存选项,但每当我关闭应用程序并重新启动它时,选项再次为空。我哪里错了?它始终加载默认值" 0"而不是记住最后的选择。
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();
}
答案 0 :(得分:1)
您正在使用两个共享首选项容器,默认容器和自定义容器容器。仅使用默认值。
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
final int[] currentChoice = {preferences.getInt("currentChoice", 0)};
答案 1 :(得分: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]);