我有一个非常简单的活动,我在每次创建程序时获取 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 游戏设置未保存。