ListPreference default value not showing up
11,630
Solution 1
I found that sometime I need to clear application data. Uninstall and reinstall the app. After that, everything works as expected.
Solution 2
I found that I have to call PreferenceManager.setDefaultValues() in my Preferences Activity in order for my default value to show up initially.
public class PreferencesActivity extends PreferenceActivity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This static call will reset default values only on the first ever read
PreferenceManager.setDefaultValues(getBaseContext(), R.xml.settings, false);
addPreferencesFromResource(R.xml.settings);
}
}
Solution 3
index = listPreference.findIndexOfValue(listPreference.value)
listPreference.setValueIndex(index)
![Emad-ud-deen](https://i.stack.imgur.com/QkTW2.jpg?s=256&g=1)
Author by
Emad-ud-deen
Updated on June 04, 2022Comments
-
Emad-ud-deen about 2 years
I tried to set the default value for a ListPreference but nothing shows up.
Can you check my code for any errors?
Thanks.
Truly, Emad
This is in the settings.xml file:
<PreferenceCategory android:title="Media:"> <CheckBoxPreference android:key="ChimeWhenMusicIsPlaying" android:title="@string/ChimeWhenMusicIsPlayingTitle" android:summary="@string/ChimeWhenMusicIsPlayingSummary" android:defaultValue="false" /> <ListPreference android:title="Chime Volume" android:key="ChimeVolume" android:summary="Select volume for the chiming sound." android:entries="@array/chimeVolumeLabels" android:entryValues="@array/chimeVolumeValues" android:defaultValue="1" /> </PreferenceCategory>
This is in the arrays file:
<resources> <string-array name="chimeVolumeLabels"> <item>Default</item> <item>Soft</item> <item>Medium</item> <item>Loud</item> </string-array> <string-array name="chimeVolumeValues"> <item>1</item> <item>2</item> <item>3</item> <item>4</item> </string-array> </resources>
-
pavel over 10 years+1 for this answer. Until preferences activity is invoked for the very first time after the application's install, the call to sharedPreferences.getString(key, null) will return null even if the android:defaultValue attribute is set in xml. If the default preferences values need to be available before the preferences activity is invoked in the application for the first time then PreferenceManager.setDefaultValues() call is a great solution.
-
runakash about 8 yearsyou saved hours of my life.
-
Kenny Worden almost 7 yearsThis may be due to the fact that Android will set the default values only once- see this
-
Amar Ilindra over 6 yearsTrue, saved hours of debugging.
-
Pointyhat over 2 years@Seraphim's I know this is old, but how can I make the prefs change without fresh install? I want the users who have already downloaded the app from store, to get the change