[Android] 数据实体的自动存取--SharedPreferences篇
本例代码以SharedPreferences为数据存取载体。
利用SharedPreferences存取一个数据,步骤如下:
[java]
SharedPreferences sharedPre = getSharedPreferences(name, mode);
存:
SharedPreferences.Editor editor = sharedPre.edit();
editor.put(key,value);
editor.commit();
取:
value = sharedPre.get(key,defaultValue);
观察以上,存取的关键是规范好对<key,value>的操作。其中key为字符串为预先定义好的。如果有多组<key,value>,则为每组想好key的名称也是一件挺纠结的事。
本文自动读取的核心在于直接使用数据实体的属性名做为key值,在存取时遍历数据实例的属性,使用反射类读取属性的名称,对属性值进行写出或写入。
首先,事先定义好可处理的存取数据类型如下:
[java]
public static final int CLZ_BYTE = 1;
public static final int CLZ_SHORT = 2;
public static final int CLZ_INTEGER = 3;
public static final int CLZ_LONG = 4;
public static final int CLZ_STRING = 5;
public static final int CLZ_BOOLEAN = 6;
public static final int CLZ_FLOAT = 7;
public static final int CLZ_DOUBLE = 8;
public static final Map<Class<?>, Integer> TYPES;
static {
TYPES = new HashMap<Class<?>, Integer>();
TYPES.put(byte.class, CLZ_BYTE);
TYPES.put(short.class, CLZ_SHORT);
TYPES.put(int.class, CLZ_INTEGER);
TYPES.put(long.class, CLZ_LONG);
TYPES.put(String.class, CLZ_STRING);
TYPES.put(boolean.class, CLZ_BOOLEAN);
TYPES.put(float.class, CLZ_FLOAT);
TYPES.put(double.class, CLZ_DOUBLE);
}
写出:
[java]
private void doSave(GoodsBean bean) {
SharedPreferences sharedPre = getSharedPreferences(GoodsBean.class.getName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPre.edit();
Class<? extends GoodsBean> clazz = bean.getClass();
Field[] arrFiled = clazz.getDeclaredFields();
try {
for (Field f : arrFiled) {
Log.d("ANDROID_LAB", "type[" + f.getType() + "] name[" + f.getName() + "]");
int type = TYPES.get(f.getType());
switch (type) {
case CLZ_BYTE:
case CLZ_SHORT:
case CLZ_INTEGER:
editor.putInt(f.getName(), f.getInt(bean));
break;
case CLZ_LONG:
editor.putLong(f.getName(), f.getLong(bean));
break;
case CLZ_STRING:
editor.putString(f.getName(), (String) f.get(bean));
break;
case CLZ_BOOLEAN:
editor.putBoolean(f.getName(), f.getBoolean(bean));
break;
case CLZ_FLOAT:
editor.putFloat(f.getName(), f.getFloat(bean));
break;
case CLZ_DOUBLE:
editor.putFloat(f.getName(), (float) f.getDouble(bean));
break;
}
}
editor.commit();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
读入:
[java]
private GoodsBean doRead() {
SharedPreferences sharedPre = getSharedPreferences(GoodsBean.class.getName(), Context.MODE_PRIVATE);
GoodsBean bean = new GoodsBean();
Class<? extends GoodsBean> clazz = bean.getClass();
Field[] arrFiled = clazz.getDeclaredFields();
try {
for (Field f : arrFiled) {
int type = TYPES.get(f.getType());
switch (type) {
case CLZ_BYTE:
byte byteValue = (byte) sharedPre.getInt(f.getName(), 0);
f.set(bean, byteValue);
break;
case CLZ_SHORT:
short shortValue = (short) sharedPre.getInt(f.getName(), 0);
f.set(bean, shortValue);
break;
case CLZ_INTEGER:
int intValue = sharedPre.getInt(f.getName(), 0);
f.set(bean, intValue);
&n
补充:移动开发 , Android ,