Android CheckBoxPreference Default Value
Asked Answered
A

3

20

I have the following XML code for my CheckBoxPreference:

<CheckBoxPreference
    android:key="pref_boot_startup"
    android:title="Auto start"
    android:defaultValue="true" />

But when I retrieve the preference in code the value is false.

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean autoStart = sharedPreferences.getBoolean("pref_boot_startup", true);

My autoStart variable returns false.

Is there a specific reason for this? Am I missing a step to set the default value to true?

Atop answered 11/10, 2010 at 15:55 Comment(0)
C
36

You have to set the defaults first:

    @Override
    protected void onCreate()
    {
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean autoStart = sharedPreferences.getBoolean("pref_boot_startup", true);

     {...}
    }
Crocket answered 12/10, 2010 at 1:22 Comment(3)
Note: I put this in a class that extends Application, NOT an activityColyer
@Colyer good shout! I was about to put it in a PreferenceFragment. Why though? :)Serviette
What purpose does the default value in the xml serve if I have to programmatically code it?Shipowner
R
12

Use junkdog's method, but for what it's worth, this is a bug in Android:

http://code.google.com/p/android/issues/detail?id=6641

Roster answered 6/12, 2010 at 12:18 Comment(0)
S
3
    // These two lines are working around an android bug:
    // http://code.google.com/p/android/issues/detail?id=6641
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.edit().putBoolean(REFRESH_COUNTER_PREF, prefs.getBoolean(REFRESH_COUNTER_PREF, true)).commit();
Statistician answered 13/1, 2012 at 12:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.