共享首选项未被清除,

时间:2013-04-22 17:49:51

标签: android sharedpreferences

我无法在点击活动中从应用中删除SharedPreferences

以下是我将值存储到UserInfoActivity SharedPreferences中的方法:

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

以下是我正在尝试清除MainActivity中SharedPreferences中的所有数据:

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

请告诉我这是怎么回事。

任何形式的帮助都将受到赞赏。

3 个答案:

答案 0 :(得分:0)

您正在使用PreferenceManager.getDefaultSharedPreferences存储,但是从getSharedPreferences("notificationCountSP")检索。它们是不同的文件,除非您将默认值设置为“notificationCountSP”。

答案 1 :(得分:0)

你可以像下面这样做

SharedPreferences userPref = getSharedPreferences(
                                    MyActivity.SHARED_PREFERENCES_FILENAME,MODE_PRIVATE);

答案 2 :(得分:0)

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

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

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

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

第一个解决方案使用默认的应用程序首选项文件,第二个解决方案使用自定义notification_prefs文件。