开发者

Android Preferences: Incorrect default values DESPITE "setDefaultValues"

开发者 https://www.devze.com 2023-04-08 01:24 出处:网络
I have a similar problem like this, so I proceeded according to the proposed solution and added this line of code to onCreate:

I have a similar problem like this, so I proceeded according to the proposed solution and added this line of code to onCreate:

PreferenceManager.setDefaultValues(this, R.xml.settings, false);

Unfortunately the problem开发者_如何学C still occurs, if the user hasn't altered the settings, still the default-value (true) from

mPreferences.getBoolean(String.valueOf(day_of_week), true)

is used instead of the default value from the XML.

One proposed to change the default-value parameter of getBoolean() to null, but this code crashes the app:

mPreferences.getBoolean(String.valueOf(day_of_week), (Boolean) null)

Any advice? Thanks in advance!


Finally it works! I really put much time and effort into searching for the error and as soon as I post here, I find it out alone ~~ thanks guys for helping me with this one.

If ever anyoneelse has this problem, the solution goes like this: Change the default Value of getBoolean() from true to false like so:

mPreferences.getBoolean(String.valueOf(day_of_week), true) -> doesn't work, it is always true no matter what happened in the XML

mPreferences.getBoolean(String.valueOf(day_of_week), false) -> it works! It's the correct default Value from the XML

I really don't understand the logic into doing this, but now it works perfectly. Seems a bit like a bug to me.


Set the third argument of setDefaultValues to true. So, PreferenceManager.setDefaultValues(this, R.xml.settings, true);

From the documentation:

public static void setDefaultValues (Context context, int resId, boolean readAgain)
If readAgain is false, this will only set the default values if this method has never been called in the past (or the KEY_HAS_SET_DEFAULT_VALUES in the default value shared preferences file is false). To attempt to set the default values again bypassing this check, set readAgain to true.
Note: this will NOT reset preferences back to their default values.

So, my understanding is:

  • If readAgain is false, it will read default values only once after the first run of app. If you add new property with default value to preferences, it will not initialized until you uninstall and install the app again.
  • If readAgain is true, it will read default values again and again on every function call. BUT, it will not reset values to default, if they already had been set or changed by the app.
0

精彩评论

暂无评论...
验证码 换一张
取 消