2013-04-22 106 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