编辑:此代码实际上有效.我在使用它的代码中遇到了问题.无论如何都要离开它以防任何人发现它有用.
我有一个类,有两个方法来编写和读取一个布尔持久化的首选项.但是,如果我写一个新值然后尝试读取它,我仍然会得到旧值.只有当我杀死应用程序并重新启动它时,我才会获得新值.知道问题是什么吗?
Context mContext;
....
public void writeFlag(boolean flag) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
Editor editor = sharedPreferences.edit();
editor.putBoolean("mykey", flag);
editor.commit();
}
public boolean readFlag() {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(mContext);
return sharedPreferences.getBoolean("mykey", false);
}
解决方法:
public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}//getPWDFromSP()
public static void saveBooleanInSP(String key, boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}//savePWDInSP()