我正在尝试共享首选项,但我无法让我的更改永久保存。
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
String lastPlayerPref = "LAST_PLAYER";
public void onCreate(Bundle savedInstanceState) {
prefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
prefsEditor = prefs.edit();
String lastPlayer = prefs.getString(lastPlayerPref, "test");
System.err.println(lastPlayer); //always outputs "test" no matter what I do
prefsEditor.putString(lastPlayerPref, "me");
prefsEditor.commit();
...
}
当我最初运行时,我希望输出“test”。当我在那之后运行它时,我希望它输出“我”。但它总是输出“测试”。在没有保存首选项的情况下,该参数不是默认值吗?
很抱歉这个混乱。谢谢!
答案 0 :(得分:0)
我想你忘记添加 .putString(lastPlayerPref,“player1”);
prefs = ProgressBarActivity.this.getSharedPreferences("myPrefs", MODE_PRIVATE);
prefsEditor = prefs.edit().putString(lastPlayerPref, "player1");
prefsEditor.commit();
String lastPlayer = prefs.getString(lastPlayerPref, "test");
System.err.println(lastPlayer);
prefsEditor = prefs.edit().putString(lastPlayerPref, "player2");
prefsEditor.commit();
lastPlayer = prefs.getString(lastPlayerPref, "test");
System.err.println(lastPlayer);
如果你在上面尝试,你会看到它会改变