2 cheli 71 cheli_71 于 2013.09.22 13:39 提问

在执行 commits 后 SharedPreferences 不能保存

我从一个简单的的 activity 中获取 SharedPrefs 的值,在每次程序创建的时候值都增加1。因此我希望当打开和关闭程序时值能增长。但是值好像没有保存。在值每次改变时我使用 commit。

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 语句中代码的输出:

Pre: 0 During: 1 Post: 999

但是执行下面的代码后:

calling prefEditor.commit();
int_out  = gameSettings.getInt("Username", 0);

SharedPref gameSettings 没有保存。

1个回答

sasuke38
sasuke38   2013.09.24 09:54
重新获取SharedPreferences来读取值
以上代码改为:
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  = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE).getInt("Username", 0);

    Log.e("Post",Integer.toString(int_out));
}
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!