Reputation: 15744
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>
Upvotes: 2
Views: 1101
Reputation: 35
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.
Upvotes: 0
Reputation: 4602
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"
/>
Upvotes: 5