我有一个非常简单的活动,我每次创建程序时都会获取SharedPrefs的值并将其递增1。因此,当我打开和关闭(退出)程序时,我希望这会继续增加。然而,似乎值不保存。我在每次更改后都使用提交。
public class SharedPreferencesActivity extends Activity {
/** Called when the activity is first created. */
public static final String PREFERENCE_FILENAME = "MyGamePreferences";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int int_out = 0;
SharedPreferences gameSettings = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = gameSettings.edit();
int_out = gameSettings.getInt("Username", 0);
Log.e("Pre",Integer.toString(int_out));
int_out = int_out + 1;
Log.e("During",Integer.toString(int_out));
prefEditor.putInt("UserName", int_out);
prefEditor.commit();
int_out = gameSettings.getInt("Username", 0);
Log.e("Post",Integer.toString(int_out));
}
}
我在Log.e语句中输出的代码是
前:0 期间:1 发布:999
所以看起来像是
之后calling prefEditor.commit();
int_out = gameSettings.getInt("Username", 0);
未保存SharedPref游戏设置。
答案 0 :(得分:2)
您使用了大写字母的一个键。改变行
prefEditor.putInt("UserName", int_out);
到
prefEditor.putInt("Username", int_out);