Setting Default Values
The preferences you create probably define some important behaviors for your application, so it‘s necessary that you initialize the associated
SharedPreferences
file with default values for each Preference
when the user first opens your application.
The first thing you must do is specify a default value for each Preference
object in your XML file using theandroid:defaultValue
attribute. The value can be any data type that is appropriate for the correspondingPreference
object. For example:
<!-- default value is a boolean --> <CheckBoxPreference android:defaultValue="true" ... /> <!-- default value is a string --> <ListPreference android:defaultValue="@string/pref_syncConnectionTypes_default" ... />
Then, from the onCreate()
method in your application‘s main activity—and in any other activity through which the user may enter your application for the first time—call setDefaultValues()
:
PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);
Calling this during onCreate()
ensures that your application is properly initialized with default settings, which your application might need to read in order to determine some behaviors (such as whether to download data while on a cellular network).
This method takes three arguments:
- Your application
Context
. - The resource ID for the preference XML file for which you want to set the default values.
- A boolean indicating whether the default values should be set more than once.
Whenfalse
, the system sets the default values only if this method has never been called in the past (or theKEY_HAS_SET_DEFAULT_VALUES
in the default value shared preferences file is false).
As long as you set the third argument to false
, you can safely call this method every time your activity starts without overriding the user‘s saved preferences by resetting them to the defaults. However, if you set it to true
, you will override any previous values with the defaults.