自己写了个读取SQLite里的数据,用起来像Gson一样简单,
开源地址:https://github.com/Yeamy/SQLiteDataSet
一、快速上手
首先创建一个要解析的Bean类
public class Fruit {
@DsIgnore
public String count; // 声明此参数不读取
public int color; // 参数名与列名相同
@DsColumn("FruitName")
public String name; // 参数名与列名不同,使用DsColumn声明
}
解析代码如下
SQLiteDatabase db = ...; // 数据库
String sql = ...; // 筛选的SQL语句
Fruit apple = DsReader.read(db, sql, Fruit.class); // 只读取一个
ArrayList<Fruit> list = DsReader.readArray(db, sql, Fruit.class);// 读取列表
这还没完,更多高级玩法,看下面:
二、把多个列打包在一个成员变量里
把多个列打包在一个成员变量里,只需要修改Bean类
public class Fruit {
...
public Skin skin; //不是基本类型,且没有声明DsColumn或DsIgnore
}
public class Skin {
public int color;
public String image;
}
ok,这就完事了
三、自定义类型
解析自定义类型成员变量,需要创建DsFactory配合DsAdapter使用
public class Fruit {
...
public FruitType type;
}
DsAdapter adapter = new DsAdapter() {
/**
* @param t
* 解析生成的对象,基础类型的成员变量已读取,可以直接使用
* @param field
* 对应需要读取的参数,使用field.getName()区分
* @param cursor
* 数据库搜索结果
* @param columnIndex
* 对应参数在rs中对应的位置
*/
@Override
public void read(Object t, Field field, Cursor cursor, int columnIndex)
throws InstantiationException, IllegalAccessException {
FruitType type = new FruitType(....);
// field.set(t, type);
Fruit f = (Fruit) t;
f.type = type;
}
};
DsFactory<Fruit> factory = new DsFactory(Fruit.class); // 实例化工厂
factory.addAdapter(FruitType.class, adapter); // 添加自定义类型
Fruit apple = factory.read(cursor); // 读取单个
factory.readArray(list, cursor); // 读取多个
tips:DsFactory读取的是Bean类的成员变量,成员变量在cursor中找不到对应列的时候不做解析,factory可以被多个cursor重复使用。