SharedPreferences will not save/load in Preference

2019-02-04 15:54发布

EDIT: The problem described below was due to a very peculiar device issue not caused by any coding-related problem.

I have a preferenceActivity in which I have many checkBoxPreferences. The checkBoxPreference is suppose to save the the default shared preferences file, and then be called again when I open the app in order to update the UI.

This does not happen like it's suppose to. If I close the app and open it back up, my values remain like they are suppose to, but if I use task manager to end the app or if I power cycle the phone (when the app is not running) then the defaultValues are called again.

So, I created a SharedPreference in my onResume() to test it.

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

I then check to see if there is a key in that sharedpreference.

pref.contains("myCheckBoxPreference");

When I close out and open it back up, it returns true. if I close with the task manager or power cycle the phone off and on, then that returns false.

So, I tried manually setting the SharedPreference

SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("myCheckBoxPreference", myCheckBoxPreference.isChecked());
editor.commit();

and then I called that when the checkboxpreference value changed. I also tried calling it in onStop and onPause. Still, if I close the app and open it back up, pref.contains returns true, but if I power cycle the phone off and back on, it returns false.

So I then tried using a SharedPreferences file.

In the class declaration:

public static final String PREFS = "prefs";

And in the onResume():

SharedPreferences pref = this.getSharedPreferences(PREFS, 0);

Same behavior, pref.contains still returns true if I just close the app and open it back up, but it returns false if I power the phone off and back on.

I then tried changing the key value of myCheckBoxPreference to something that did NOT match the xml key for the CheckBoxPreference, and it still had the same effect.

And I uninstalled the application from the phone, then powered the phone off and back on, and then re-installed, and it still has the same effect.

7条回答
放荡不羁爱自由
2楼-- · 2019-02-04 16:27

Try clearing the editor before you set your values. I had the same problem and it worked for me. Example:

Editor e = PreferenceManager.getDefaultSharedPreferences(getParent()).edit();
e.clear();
e.putStringSet(key, value);
查看更多
登录 后发表回答