0

I'm unable to delete SharedPreferences from the app on click event.

Here is how I'm storing the value into UserInfoActivity SharedPreferences:

SharedPreferences notificationCountSP = PreferenceManager
             .getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor notificationEditor = perkBalance.edit();
notificationEditor.putString("notificationCount",notificationCountValue);
notificationEditor.commit();

And here is how I'm trying to clear all data in SharedPreferences from MainActivity:

SharedPreferences clearNotificationSP = getSharedPreferences(
                "notificationCountSP", 0);
SharedPreferences.Editor editor = clearNotificationSP.edit();
editor.remove("notificationCount");
editor.clear();
editor.commit();

Please tell what am I doing wrong with this.

Any kind of help will be appreciated.

Anupam
  • 3,742
  • 18
  • 55
  • 87

3 Answers3

0

You are using PreferenceManager.getDefaultSharedPreferences to store but retrieving from getSharedPreferences("notificationCountSP"). They are different files unless you set the default one to "notificationCountSP".

  • `PreferenceManager.setDefaultValues(context, resId, true)`, where resId is the resource ID of the preference file. If you are not willing to create your own pref file, you could just use `getApplicationContext().getSharedPreferences("notificationCountSP", mode)` and store the value. – Vinicius Rosa Apr 22 '13 at 18:04
0

You can do it like below

SharedPreferences userPref = getSharedPreferences(
                                    MyActivity.SHARED_PREFERENCES_FILENAME,MODE_PRIVATE);
Adesh Atole
  • 766
  • 1
  • 8
  • 22
0
SharedPreferences notificationCountSP = PreferenceManager
                     .getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor notificationEditor = notificationCountSP.edit();
notificationEditor.putString("notificationCount", notificationCountValue);
notificationEditor.commit();

notificationEditor.remove("notificationCount");
notificationEditor.commit();

or

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

editor.remove("notificationCount");
editor.commit();

First solution uses the default application preferences file, and the second a custom notification_prefs file.

ba-res-ba
  • 150
  • 1
  • 9
  • Hey, one quick doubt here, after doing your second method, I'm trying to print the value of the `editor.remove("notificationCount");` and it is printing in the log. Why is that happening? – Anupam Apr 24 '13 at 10:52