我在onPause方法中保存了一个布尔值的状态。我尝试过使用editor.apply()和editor.commit(),但仍然没有保存这些值。 这是onPause方法:
@Override
protected void onPause() {
SharedPreferences.Editor editor = preferences.edit();
editor.clear(); //I have tried omitting it
editor.putBoolean(MUTE_TAG,mute);
editor.apply(); // I tried editor.commit() but with no effect
boolean mute1 = preferences.getBoolean(MUTE_TAG,false);
Log.d(TAG,"Values:\n"+ "mute1 " + mute1 + " mute);
super.onPause();
}
注意:当我尝试从不同的活动再次访问SharedPreferences中的值时,它不会更新。这是设置代码
public static boolean mute;
public static final String PREFS = "prefs";
init(Context context) {
preferences = context.getSharedPreferences(PREFS,MODE_PRIVATE);
mute = preferences.getBoolean(MUTE_TAG,false);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG,"MUTE PRESSED");
mute = isChecked;
break;
}
答案 0 :(得分:0)
What about after saving? Does the logcat show the current/expected value?
Here is what has worked for me:
Before : private boolean mute = true;
but after sending the app to background. the result showed it true. While the default value is false;
COPIED YOUR CODE AS-IS
ONLY PROBLEM: Unclosed string literal
@Override
protected void onPause() {
SharedPreferences preferences = getSharedPreferences("SHARED_PREFERENCES_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
mute = !mute ;
Log.d(TAG, "UPDATED MUTE VALUE :: " + mute);
editor.clear(); //I have tried omitting it
editor.putBoolean(MUTE_TAG,mute);
editor.apply(); // I tried editor.commit() but with no effect
boolean mute1 = preferences.getBoolean(MUTE_TAG,false);
Log.d(TAG,"Values:\n"+ "mute: " + mute1 + " mute");
super.onPause();
}
SOLUTION #2
It is connected to this What's the difference between commit() and apply() in Shared Preference . Try using commit again, commit will block super.onPause
from executing thus making sure it saves
SOLUTION #3
Your activities are calling onPause
after onCreate
thus saving back the default mute
value. Therefore, Create a class & add STATIC PUBLIC /PUBLIC STATIC variables that will store the mute value & only save it when an activity is being destroyed. This static variable will not change it's value across activities