0

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.

Ray J
  • 44
  • 3
  • 9

2 Answers2

1

Try replacing

SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

with

PreferenceManager.getDefaultSharedPreferences(context);

I believe you're attempting to retrieve "notification_key" from the wrong SharedPreferences, which is why it's always using the default value of true and showing your notification.

Edit: You can check to see whether the SharedPreferences you're using contains the "notification_key" key with the contains() method.

PPartisan
  • 8,173
  • 4
  • 29
  • 48
  • I've used the getDefaulSharedPreferences(context) method but same thing happens, checked with contains method if the key exists and that returns true. When using getBoolean method whatever boolean defValue I provide is gets set and shows notifications, if set to true no matter whatever the switch's state is and, if defValue set to false then it doesn't show notifications even if the switch state is on. I just can't figure out what's going on there. – Ray J Jul 08 '17 at 08:41
0

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.

Ray J
  • 44
  • 3
  • 9