2011-03-09 69 views
1

有沒有辦法徹底擺脫偏好?看起來clear()和remove(key)並沒有完全擺脫偏好。如果你調用clear()然後調用SharedPreferences.contains(「key」),它將返回true。擺脫偏好

請注意,我也犯()clear()。

+0

如果我們能看到你的一些代碼會更容易。通過調用清除,然後提交應該工作。這聽起來像命令沒有被調用。 – Phobos 2011-03-09 08:24:08

+0

正在調用這些命令。問題是VALUE被清除,但我定義的屬性/密鑰仍然存在。 – locoboy 2011-03-09 17:40:04

回答

1

這裏是如何實現的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(); 
     }  
    } 
} 
0

clear()是不明確的,它首先清除偏好,然後用修改的preference. replace()重新初始化可以滿足您的需要,只需傳遞一個空的地圖。

+0

是否有替換()的文檔?我找不到它 – locoboy 2011-03-09 08:43:56

+0

哦,這是一個內部API。我不知道。 – 2011-03-09 08:57:41

+0

函數'replace()'未放置在SharedPreferences接口中,但此函數存在於SharedPreferences的SharedPreferencesImpl實現中。我建議避免使用它。 – inazaruk 2011-03-09 09:15:34