Is there a way to completely get rid of a preference? It seems that clear() and remove(key) doesn't开发者_如何学Python get rid of the preference completely. If you call clear() then call SharedPreferences.contains("key"), it returns true.
Note that I do also commit() the clear().
Here is how clear()
implemented:
public Editor clear() {
synchronized (this) {
mClear = true;
return this;
}
}
public boolean commit() {
//...
synchronized (this) {
if (mClear) {
mMap.clear();
mClear = false;
}
}
//...
}
Here is how contains(String key)
implemented:
public boolean contains(String key) {
synchronized (this) {
return mMap.containsKey(key);
}
}
You can see code yourself here. (Note that preference change listeners are not called when all preferences are cleared).
The implementation looks fine to me, and most likely that it's problem with your code.
Here is my short example application which verifies that clear()
works correctly.
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();
}
}
}
clear()
is ambiguous, it first clear the preferences,then reinitialize with the modified preference. replace()
could meet your need,just pass an empty map to it.
精彩评论