Search code examples
androidandroid-preferences

Setting default CheckBoxPreference always on


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>

Solution

  • 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"
    />