Android SharedPreferences存储的正确写法

SharedPreferences 特点

即便是Android小白都知道的SharedPreferences的用法,这是保存数据最简便的方法,但是不处理好的话后期维护将是一个巨大的坑。那么该如何处理好SharedPreferences才方便维护呢。先从它的特点开始入手吧。

  1. 通过Context.getSharedPreferences()获取的SharedPreferences是一个单例
  2. SharedPreferences.edit()每次都会创建一个新的编辑对象,commit()之前一切改动都无效

SharedPreferences的具体实现并不在公开API内,创建方法只有通过Context获取。具体实现我们不去研究,通过Log打印每次获取的对象都是同一个,同样的方法可知道每次edit()都会得到不同的对象。

难以维护的 SharedPreferences

SharedPreference userPreferences = context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
userPreferences.edit()
  .putString("id", "myId")
  .putString("name", "myName")
  .putString("head", "myHead")
  .commit();
Log.e("id", userPreferences.getString("id",""));
Log.e("name", userPreferences.getString("name",""));
Log.e("head", userPreferences.getString("head",""));

如上一段SharedPreferences保存和读取的方法非常简便,正因此才不易维护,可能因为写错Key而找不出问题所在,当然一般我们都会把Key写成静态常量。但随着项目增大,可能需要多处修改用户信息,每次都要一个个put(), 除了写着厌烦看着难受,当遇到需要增加或减少字段时也非常不便。

SharedPreferences 该这么写

如果能保留原有写法,又能规范方法那是最好不过了,看下SharedPreferences的接口方法并不多,很容易就写个包装类封装下。

import android.content.SharedPreferences;
import android.support.annotation.Nullable;

import java.util.Map;
import java.util.Set;

/**
 * SharedPreferences 包装类
 * Created by wittytutu on 17-3-29.
 */

public class PreferencesWrapper implements SharedPreferences {

  protected SharedPreferences mPreferences;

  public PreferencesWrapper(SharedPreferences preferences) {
    mPreferences = preferences;
  }

  @Override
  public Map getAll() {
    return mPreferences.getAll();
  }

  @Nullable
  @Override
  public String getString(String key, @Nullable String defValue) {
    return mPreferences.getString(key, defValue);
  }

  @Nullable
  @Override
  public Set getStringSet(String key, @Nullable Set defValues) {
    return mPreferences.getStringSet(key, defValues);
  }

  @Override
  public int getInt(String key, int defValue) {
    return mPreferences.getInt(key, defValue);
  }

  @Override
  public long getLong(String key, long defValue) {
    return mPreferences.getLong(key, defValue);
  }

  @Override
  public float getFloat(String key, float defValue) {
    return mPreferences.getFloat(key, defValue);
  }

  @Override
  public boolean getBoolean(String key, boolean defValue) {
    return mPreferences.getBoolean(key, defValue);
  }

  @Override
  public boolean contains(String key) {
    return mPreferences.contains(key);
  }

  @Override
  public EditorWrapper edit() {
    return new EditorWrapper(mPreferences.edit());
  }

  @Override
  public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
    mPreferences.registerOnSharedPreferenceChangeListener(listener);
  }

  @Override
  public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
    mPreferences.unregisterOnSharedPreferenceChangeListener(listener);
  }

  public static class EditorWrapper implements Editor {
    protected Editor mEditor;

    public EditorWrapper(Editor editor) {
      mEditor = editor;
    }

    @Override
    public EditorWrapper putString(String key, @Nullable String value) {
      mEditor.putString(key, value);
      return this;
    }

    @Override
    public EditorWrapper putStringSet(String key, @Nullable Set values) {
      mEditor.putStringSet(key, values);
      return this;
    }

    @Override
    public EditorWrapper putInt(String key, int value) {
      mEditor.putInt(key, value);
      return this;
    }

    @Override
    public EditorWrapper putLong(String key, long value) {
      mEditor.putLong(key, value);
      return this;
    }

    @Override
    public EditorWrapper putFloat(String key, float value) {
      mEditor.putFloat(key, value);
      return this;
    }

    @Override
    public EditorWrapper putBoolean(String key, boolean value) {
      mEditor.putBoolean(key, value);
      return this;
    }

    @Override
    public EditorWrapper remove(String key) {
      mEditor.remove(key);
      return this;
    }

    @Override
    public EditorWrapper clear() {
      mEditor.clear();
      return this;
    }

    @Override
    public boolean commit() {
      return mEditor.commit();
    }

    @Override
    public void apply() {
      mEditor.apply();
    }
  }
}

接下来的使用就简单了

public class UserInfoPreferences extends PreferencesWrapper {
  private static final String NAME = "UserInfo";

  public static final KEY_ID = "id"
  public static final KEY_NAME = "name";
  public static final KEY_HEAD = "head";
  public static final KEY_SEX = "sex";

  private static volatile UserInfoPreferences mPreferences;

  public static UserInfoPreferences getInstance(Context context){
    if(mPreferences == null) {
      synchronized (UserInfoPreferences.class){
        if(mPreferences == null) {
          SharedPreferences preferences = context.getApplicationCtontext().getShaedPreferences(NAME, Context.MODE_PRIVATE);
          mPreferences = new UserInfoPreferences(preferences);
        }
      }
    }
    return mPreferences;
  }

  public UserInfoPreferences(SharedPreferences preferences) {
    super(preferences);
  }

  // 获取用户信息
  public UserInfo getUserInfo(){
    String id = mPreferences.getString(KEY_ID, "");
    String name = mPreferences.getString(KEY_NAME, "");
    String head = mPreferences.getString(KEY_HEAD, "");
    return new UserInfo(id, name, head);
  }

  @Override
  public Editor edit(){
    return new Editor(mPreferences.edit());
  }

  public static class Editor extends EditorWrapper {

    public Editor(SharedPreferences.Editor editor) {
      super(editor);
    }

    // 保存用户信息
    public Editor putUserInfo(String id, String name, String head) {

      mEditor.putString(KEY_ID, id)
          .putString(KEY_AME, name)
          .putString(KEY_HEAD, head);
      return this;
    }

    // 清空用户信息
    public Editor clearUserInfo() {

      mEditor.remove(KEY_ID)
          .remove(KEY_NAME)
          .remove(KEY_HEAD);
      return this;
    }
  }
}

调用即方便扩展,也保留了原有方法。

UserInfoPreferences preferences = UserInfoPreferences.getInstance(context);
preferences.edit()
  .clearUserInfo()
  .putUserInfo("myId", "myName", "myHead")
  .putInt(KEY_SEX, 0)
  .commit();
UserInfo userInfo = preferences.getUserInfo();
int sex = preferences.getInt(KEY_SEX, 0);

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!