Android settings: invalid defaults DESPITE "setDefaultValues"

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

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

Unfortunately, the problem still occurs if the user has not changed the settings, but the default value (true) of

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

used instead of the default value from XML.

One suggested changing the default getBoolean () parameter to null, but this code causes the application to crash:

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

Any tips? Thanks in advance!

+6
source share
2 answers

Finally it works! I really devote a lot of time and effort to finding a mistake, and as soon as I publish here, I find it alone. ~~ thanks guys for helping me with this.

If this problem has ever occurred, the solution will look like this: Change the default value of getBoolean() from true to false as follows:

mPreferences.getBoolean(String.valueOf(day_of_week), true) does not work, this is always true, regardless of what happened in the XML

mPreferences.getBoolean(String.valueOf(day_of_week), false) it works! This is the correct default value from XML

I really don't understand the logic behind this, but now it works great. It seems like a mistake.

+5
source

Set the third argument to 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, it will only set default values โ€‹โ€‹if this method has never been called in the past (or KEY_HAS_SET_DEFAULT_VALUES in the general default settings file is false). To try again to set the default values โ€‹โ€‹bypassing this check, set readAgain to true.
Note: this will NOT match reset to their default values.

So, I understand:

  • If readAgain is false , it will only read the default values โ€‹โ€‹once after the first launch of the application. If you add a new property to the default value in the settings, it will not be initialized until you uninstall and reinstall the application.
  • If readAgain is true , it will read the default values โ€‹โ€‹again and again with every function call. BUT, this will not reset the default values โ€‹โ€‹if they have already been installed or modified by the application.
+3
source

Source: https://habr.com/ru/post/898200/


All Articles