android中sharedpreference封装思路

来源:互联网 发布:淘宝消费者投诉电话 编辑:程序博客网 时间:2024/06/06 12:56

Android中SharedPreference封装思路

涉及到的方法与类

  • context.getSharedPreferences(String, int);
  • preference.edit();
  • editor.commit();

关键的两个方法:存储与获取

存储:根据存储的value类别形成了多个方法,有两个值得思考的点:
* 两个方法重复的代码要不要使用方法复用
* 一次只存储一个value是不是过于低效

思考得出的暂时答案:
* 复用的根本目的是节约编码时间,以后的易读性。如果两者因为使用同一方法并没有提升,反而浪费了不少时间,则不需要
* 使用SharedPreferences作持久化的情况是很少的,这种方法所造成的低效是可以容忍的

public static void setPreferenceInfo(String type, Context c, String key,            String value) {        try {            SharedPreferences mPreferences = c.getSharedPreferences(type, 0);            Editor mEditor = mPreferences.edit();            if (key != null) {                mEditor.putString(key, value);            }            mEditor.commit();        } catch (Exception e) {            e.printStackTrace();        }    }public static void setPreferenceInfo(String type, Context c, String key,            boolean value) {        try {            SharedPreferences mPreferences = c.getSharedPreferences(type, 0);            Editor mEditor = mPreferences.edit();            if (key != null) {                mEditor.putBoolean(key, value);            }            mEditor.commit();        } catch (Exception e) {            e.printStackTrace();        }    }

获取

public static String getPreferenceInfo(String type, Context c, String key) {        String value = "";        SharedPreferences preferences = c.getSharedPreferences(type, 0);        if (preferences == null) {            return value;        }        value = preferences.getString(key, "");        return value;    }    public static long getPreferenceLong(Context c, String type, String key) {        long value = 0;        SharedPreferences preferences = c.getSharedPreferences(type, 0);        if (preferences == null) {            return value;        }        value = preferences.getLong(key, 0);        return value;    }

不变常量的命名规范

类别使用TYPE_开头

public static final String TYPE_USERINFO = "userinfo";public static final String TYPE_SDK = "sdk";

要取的键任意

public static final String USER_HEX = "user_hex";public static final String USER_ACCOUNT = "uid";public static final String USER_NICK_NAME = "username";
0 0
原创粉丝点击