共享首选项问题,在调用clear后未释放该值



在我的应用程序中,我想清除SharedPreferences按钮单击。这就是我用来在其中存储值的方法:

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

onClick()的代码如下:

SharedPreferences clearedNotificationSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editorSP = clearedNotificationSP.edit();
editorSP.remove("notificationCount");
editorSP.commit();
System.out.println("Saved in SP clearedNotification: "+ clearNotification);

我在清除它后打印值,但我仍然得到相同的值。

我错过了什么?

getDefaultSharedPreferencesgetSharedPreferences("notification_prefs", );

返回两个不同的SharedPreferences。由于在notification_prefs中添加了notificationCount,因此应该使用getSharedPreferences("notification_prefs", );

检索SharedPreference。

getDefaultSharedPreferences使用默认的首选项文件名,而getSharedPreferences使用您作为参数

提供的文件名。