Reputation: 51
I want to check the value (true/false) of a boolean from a SwitchPrefernce/CheckBoxPreference from the SettingsActivity.java
In the MainActivity is the following code:
SharedPreferences notification1, notification2, notification3;
notification1 = getSharedPreferences("sound_on_create", Context.MODE_PRIVATE);
notification2 = getSharedPreferences("vibrate_on_create", Context.MODE_PRIVATE);
notification3 = getSharedPreferences("remove_onklick", Context.MODE_PRIVATE);
boolean playSound = notification1.getBoolean("sound_on_create", false);
boolean vibrate = notification2.getBoolean("vibrate_onklick", false);
boolean removeOnklick = notification3.getBoolean("remove_onklick", true);
And the definition in the SettingsActivity:
<SwitchPreference
android:title="Text 1"
android:summary="summary 1"
android:key="sound_on_create"
android:defaultValue="true"/>
<SwitchPreference
android:title="Text 2"
android:summary="summary 2"
android:key="vibrate_on_create"
android:defaultValue="true"/>
<SwitchPreference
android:title="Text 3"
android:summary="summary 3"
android:key="remove_onclick"
android:defaultValue="true"/>
And if I get the values with Log.d the values are always false false true So, how can I get the value which the user can set in the settings?
Upvotes: 2
Views: 525
Reputation: 43322
It looks like you're using a PreferenceActivity, so the values will be stored in the default SharedPreferences for your app.
Your current code is looking at three separate preference files (SharedPreferences are stored in xml files).
Instead of looking in the three files where the values do not exist, get them from the default SharedPreferences file, which is where they do exist:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean playSound = sharedPrefs.getBoolean("sound_on_create", false);
boolean vibrate = sharedPrefs.getBoolean("vibrate_on_create", false);
boolean removeOnklick = sharedPrefs.getBoolean("remove_onclick", true);
//testing:
Toast.makeText(this, "values: " + playSound + " " + vibrate + " " + removeOnklick, Toast.LENGTH_LONG).show();
Upvotes: 1
Reputation: 519
If you're saving preferences from a preference xml file, you will want to use:
getDefaultSharedPreferences(this)
instead of
getSharedPreferences("sound_on_create", Context.MODE_PRIVATE);
EDIT: typo
Upvotes: 0