Initialize preferences from XML in the main Activity [duplicate]

Solution 1:

In onCreate() of your main Activity just call the PreferenceManager.setDefaultValues() method.

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

This will read your preference.xml file and set the default values defined there. 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.

Solution 2:

I'll be brief. :)

strings.xml (actually I have prefs.xml exclusively for preferences):

<string name="pref_mypref_key">mypref</string>
<string name="pref_mypref_default">blah</string>

preferences.xml:

android:key="@string/pref_mypref_key"
android:defaultValue="@string/pref_mypref_default"

MyActivity.java:

String myprefVal = prefs.getString(getString(R.string.pref_mypref_key), getString(R.string.pref_mypref_default));

Solution 3:

Your call to getString() has null as the second parameter. Change that to be the default value you want.