Anupam
Anupam

Reputation: 3752

Shared Preferences issue, not freeing the value after calling clear

In my application I want to clear SharedPreferences on button click. This is what I'm using for storing values in it:

SharedPreferences clearNotificationSP = getSharedPreferences("notification_prefs", 0);
SharedPreferences.Editor Notificationeditor = clearNotificationSP.edit();
Notificationeditor.putString("notificationCount", notificationCountValue);
Notificationeditor.commit();

And the following code on onClick():

SharedPreferences clearedNotificationSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editorSP = clearedNotificationSP.edit();
editorSP.remove("notificationCount");
editorSP.commit();

System.out.println("Saved in SP clearedNotification: "+ clearNotification);

I was printing the value after clearing it but still I was getting the same value.

What am I missing?

Any kind of help will be appreciated.

Upvotes: 0

Views: 94

Answers (1)

Blackbelt
Blackbelt

Reputation: 157447

getDefaultSharedPreferences and getSharedPreferences("notification_prefs", );

returns two different SharedPreferences. Since you are adding notificationCount inside notification_prefs, you should retrieve SharedPreference with getSharedPreferences("notification_prefs", );

getDefaultSharedPreferences uses a default preference-file name, while getSharedPreferences use the filename you provided as paramter

Upvotes: 2

Related Questions