1

我正在尝试共享首选项,但我无法持久保存我的更改。

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

    ...
}

当我最初运行它时,我希望输出“测试”。当我在那之后运行它时,我希望它输出“我”。但它总是输出“测试”。如果没有保存任何偏好,那么该参数不只是默认值吗?

对困惑感到抱歉。谢谢!

4

1 回答 1

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

如果你在上面尝试,你会看到它会改变

于 2012-12-06T22:22:45.807 回答