2

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?

1
  • when you are saving values in sharedpreference are you doing commit ? it looks its retrieving default values
    – ASP
    Jun 29, 2015 at 19:06

2 Answers 2

1

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();
0
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.