Search code examples
androidsharedpreferencesandroid-preferencesandroid-sharedpreferencesswitchpreference

Android SwitchPreference not working


I'm trying to retrieve the SwitchPreference's value using SharedPreferences but it isn't working. I'm using SwitchPreference so that user can turn on/off notifications, but it shows notifications no matter whatever the value is. Here's the code.

NotificationUtils.java

SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
    if (preferences.getBoolean("notification_key", true)) {
        notificationManager.notify(NOTIFICATION_ID + rowId, notBuilder.build());
    }

preferences.xml

<SwitchPreference
    android:contentDescription="Turn notifications on/off"
    android:defaultValue="true"
    android:key="notification_key"
    android:summaryOff="Off"
    android:summaryOn="On"
    android:title="Notifications" />

I also have overridden and registered the OnSharedPreferenceChange listener in SettingsFragment.java.


Solution

  • I solved it, actually the value wasn't toggling, in settings screen the Switch was turning off and on but the value remained the default. Solved it by setting the new value in OnPreferenceChangeListener and that worked.