This question already has an answer here:
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.
I'll be brief. :)
strings.xml (actually I have prefs.xml exclusively for preferences):
preferences.xml:
MyActivity.java:
In
onCreate()
of your mainActivity
just call thePreferenceManager.setDefaultValues()
method.This will read your
preference.xml
file and set the default values defined there. Setting thereadAgain
argument tofalse
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 yourActivity
is created.Your call to
getString()
hasnull
as the second parameter. Change that to be the default value you want.