Android SharedPreferences存储的正确写法

Android SharedPreferences存储的正确写法,第1张

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

SharedPreferences 特点

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

通过Context.getSharedPreferences()获取的SharedPreferences是一个单例
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);

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

总结

以上是内存溢出为你收集整理的Android SharedPreferences存储的正确写法全部内容,希望文章能够帮你解决Android SharedPreferences存储的正确写法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1146054.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存