android sharedPreferences的清除功能不起作用

时间:2018-07-05 10:02:47

标签: android singleton sharedpreferences clear android-sharedpreferences

我的偏好清除不起作用。

这是我的PreferencManager.java

public class PreferenceManager {
  private static final String PREF_NAME = "my_prefs.xml";

  private static PreferenceManager instance;
  private SharedPreferences mPrefs;
  private SharedPreferences.Editor mEditor;

  public static PreferenceManager getInstance(Context context) {
      if (instance == null) {
          instance = new PreferenceManager(context);
      }
      return instance;
  }


  private PreferenceManager(Context context) {
      mPrefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
      mEditor = mPrefs.edit();
  }

  private static final String UUID = "UUID";
  private String uuid = "";

  public void setUuid(String key) {
      this.uuid = key;
      clear(UUID);
      mEditor.putString(UUID, key);
      mEditor.commit();
  }

  public String getUuid() {
      if (uuid.equals("")) {
          uuid = mPrefs.getString(UUID, "");
      }
      return uuid;
  }
  //clear
  public void clear(String key) {
      mEditor.remove(key);
      mEditor.commit();
  }
  public void allClear(){
      mEditor = mPrefs.edit();
      mEditor.clear();
      mEditor.commit();
  }
}

当我在活动中使用它时,

PreferenceMangaer.getInstance(getApplicationContext).setUUID("ok");

String result= PreferenceMangaer.getInstance(getApplicationContext).getUUID;

调试时,clear(UUID)不起作用,allClear也是如此。 为什么它不起作用?

我同时尝试commit()和apply()。

我正在等待您的帮助 谢谢

2 个答案:

答案 0 :(得分:1)

您也没有清除全局uuid

  public void allClear(){
      this.uuid = ""; // Clears the global uuid.
      mEditor = mPrefs.edit();
      mEditor.clear();
      mEditor.commit();
  }

这就是为什么您的getUuid获得与以前相同的结果的原因。

您不必存储uuid的本地引用。

  private static final String UUID = "UUID";

  public void setUuid(String key) {
      mEditor.putString(UUID, key);
      mEditor.apply(); // better use apply() instead commit()
  }

  public String getUuid() {
      return mPrefs.getString(UUID, "");
  }

  //clear
  public void clear(String key) {
      mEditor.remove(key);
      mEditor.apply();
  }
  public void allClear(){
      mEditor.clear();
      mEditor.apply(); 
  }

答案 1 :(得分:0)

使用键和编辑器功能。

    SharedPreferences Prefs =PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = Prefs.edit();
    editor.remove(String key);
    editor.apply()