50

My problem is that when I start application and user didn't open my PreferenceActivity so when I retrieve them don't get any default values defined in my preference.xml file.

preference.xml file:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="applicationPreference" android:title="@string/config"
    >
    <ListPreference
            android:key="pref1"
            android:defaultValue="default"
            android:title="Title"
            android:summary="Summary"
            android:entries="@array/entry_names"
            android:entryValues="@array/entry_values"
            android:dialogTitle="@string/dialog_title"
    />                  
</PreferenceScreen>

Snippet from my main Activity (onCreate method):

    SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);        
    String pref1 = appPreferences.getString("pref1", null);

In result I end up with a null value.

gobernador
  • 5,659
  • 3
  • 32
  • 51
pixel
  • 24,905
  • 36
  • 149
  • 251

3 Answers3

112

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.

David Webb
  • 190,537
  • 57
  • 313
  • 299
14

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));
yanchenko
  • 56,576
  • 33
  • 147
  • 165
  • Thanks, this actually is answer to my another question about where to store preference keys :) If I'll be able to combine it with best answer to this question it will be great! – pixel May 20 '10 at 19:04
  • 2
    Apparently, in this example, this line would appear in `MyActivity.java` before the assignment of `myprefVal`: `SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);` – hotshot309 Dec 30 '11 at 17:01
  • 4
    This works, but should this really be necessary? – JohnyTex Oct 16 '14 at 18:51
8

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

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 6
    This is a very elegant solution. +1. However, to achieve what the OP wanted, the PreferenceManager.setDefaultValues() is the solution. – ef2011 May 09 '11 at 01:58