2013-04-22 80 views
0

我无法从应用程序点击事件中删除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(); 

请告诉我在做什么错了。

任何形式的帮助将不胜感激。

+0

尝试调用通知编辑器(在第一个块)删除操作..我想,你编辑两个单独的首选项文件。 – 2013-04-22 17:54:27

+0

尝试以相同的方式并在相同的上下文中检索SharedPrefences.Editor。 – hovanessyan 2013-04-22 17:55:08

+0

@hovanessyan你有什么我可以看的。我无法得到你。 – Anupam 2013-04-22 17:59:02

回答

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文件第二定制。

+0

嘿,这里有一个疑问,在做第二个方法之后,我试图打印'editor.remove(“notificationCount”);'它正在日志中打印。为什么会发生? – Anupam 2013-04-24 10:52:53

0

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

+0

如何设置?你能给我一个示例代码。 – Anupam 2013-04-22 17:56:35

+0

'PreferenceManager.setDefaultValues(context,resId,true)',其中resId是首选项文件的资源ID。如果你不想创建自己的pref文件,你可以使用getApplicationContext()。getSharedPreferences(“notificationCountSP”,模式)'并存储值。 – 2013-04-22 18:04:40

0

你可以像下面

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

这是为了存储值的权利?如何根据您的情况储存和删除这些值。 – Anupam 2013-04-22 18:00:10

+0

[This](http://stackoverflow.com/questions/3687315/deleting-shared-preferences)可能会帮助你 – 2013-04-25 17:04:36