开发者

Get rid of a preference

开发者 https://www.devze.com 2023-02-15 21:39 出处:网络
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 SharedPrefer

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号