有沒有辦法徹底擺脫偏好?看起來clear()和remove(key)並沒有完全擺脫偏好。如果你調用clear()然後調用SharedPreferences.contains(「key」),它將返回true。擺脫偏好
請注意,我也犯()clear()。
有沒有辦法徹底擺脫偏好?看起來clear()和remove(key)並沒有完全擺脫偏好。如果你調用clear()然後調用SharedPreferences.contains(「key」),它將返回true。擺脫偏好
請注意,我也犯()clear()。
這裏是如何實現的clear()
:
public Editor clear() {
synchronized (this) {
mClear = true;
return this;
}
}
public boolean commit() {
//...
synchronized (this) {
if (mClear) {
mMap.clear();
mClear = false;
}
}
//...
}
這裏是如何實現的contains(String key)
:
public boolean contains(String key) {
synchronized (this) {
return mMap.containsKey(key);
}
}
你可以看到自己的代碼here。 (請注意,如果清除所有首選項,則不會調用首選項更改偵聽器)。
這個實現對我來說看起來很好,很可能它是你的代碼的問題。 這是我的簡短示例應用程序,它驗證clear()
是否正常工作。
public class TestPrefClear extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean("TEST", true).commit();
if(!prefs.contains("TEST")){
throw new IllegalStateException();
}
prefs.edit().clear().commit();
if(prefs.contains("TEST")){
throw new IllegalStateException();
}
}
}
如果我們能看到你的一些代碼會更容易。通過調用清除,然後提交應該工作。這聽起來像命令沒有被調用。 – Phobos 2011-03-09 08:24:08
正在調用這些命令。問題是VALUE被清除,但我定義的屬性/密鑰仍然存在。 – locoboy 2011-03-09 17:40:04