2

I have a CheckBoxPreference and I want it to be checked by default; but it is not working.

This is my code:

In my extends Application class:

@Override
public void onCreate() {
    super.onCreate();

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.getBoolean("notify", true);

}

And the actual Pref:

    <CheckBoxPreference
        android:key="notify"
        android:title="Push Notifications"
        android:summary="Receive status bar alerts"/>
    </PreferenceCategory>
TheLettuceMaster
  • 15,594
  • 48
  • 153
  • 259

2 Answers2

5

You need to add the default value to your xml. Notice the android:defaultValue="true"

android:defaultValue="true"

<CheckBoxPreference
    android:key="notify"
    android:title="Push Notifications"
    android:summary="Receive status bar alerts"
    android:defaultValue="true"
/>
kevskree
  • 4,442
  • 3
  • 24
  • 32
  • Wow that was easy. I thought I looked for a default tag in the `xml`. Would still need the other java code included? – TheLettuceMaster Sep 23 '14 at 18:35
  • 1
    Yes, the other key is the `PreferenceManager.setDefaultValues(this, R.xml.preferences, false);`. This will load the default values from the xml and save them to the SharedPreferences. – kevskree Sep 23 '14 at 18:37
  • @kevskree So what is he/she says: http://stackoverflow.com/questions/3907830/android-checkboxpreference-default-value – Dr.jacky Oct 05 '15 at 11:51
0

I just wanted to add something really important to the accepted answer. Yes all you have to do is add the default values as they say, and if you look in the comments, someone else mentions that you need to actually set the default values with this line of code ->

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

You can put that line of code in your OnCreate method in your settings activity, or you can call it in your preferences fragment.

And this is the important thing! You will not see your default settings get loaded if you've already run your app at least once. That's because the default values are only set once in order to prevent the loss of user settings.

So if you want to see your default settings and make sure they're working, uninstall your app and then rerun it.

John Conde
  • 217,595
  • 99
  • 455
  • 496
user3308807
  • 25
  • 1
  • 8