Android Preferences: How to load the default values when the user hasn't used the preferences-screen?

this question is similar to mine:

initialize-preferences-from-xml-in-main-activity

Just use this code in onCreate method:

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

It will load your preferences from XML, and last parameter (readAgain) will guarantee that user preferences won't be overwritten. That means setting the readAgain argument to false means this will only set the default values if this method has never been called in the past so you don't need to worry about overriding the user's settings each time your Activity is created

Take a look into PreferenceManager.setDefaultValues in Android API for further investigation.


Be aware that if you are using
getSharedPreferences(String sharedPreferencesName, int sharedPreferencesMode)

to retrieve preferences you have to use
PreferenceManager.setDefaultValues(Context context, String sharedPreferencesName, int sharedPreferencesMode, int resId, boolean readAgain)
to set defaults!

For example:
PreferenceManager.setDefaultValues(this, PREFS_NAME, Context.MODE_PRIVATE, R.xml.preference, false);

I hope this can help someone.


in Pixel's accepted answer:

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

it is stated that the false means that defaults won't be overwritten. This is not what it does, it is just an efficiency flag to stop the parsing if your application has more than one entry point. Unfortunately the test is not made per preference file, so if you have more than one preference file you must code true on all but the first.

If you are worried about efficiency, you could code something like this.

final static private int SPL = 1;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (sp.getInt("spl", 0) != SPL)
{
    PreferenceManager.setDefaultValues(this, R.xml.prefs1, true);
    PreferenceManager.setDefaultValues(this, R.xml.prefs2, true);
    sp.edit().putInt("spl", SPL).apply();
}

If you ever add more shared preferences, just set SPL to a hight number.