定义一个IDaoInf接口:
public interface IDaoInf<T> {
void init(SQLiteDatabase sqLiteDatabase,Class<T> mClazz);
public int insert(T t);
public void insert(List<T> data);
public int delete(T t);
public List<T> queryAll();
}
实现一个工厂类:
public class DaoFactory {
private static DaoFactory mDaoFactory;
private SQLiteDatabase mDatabase;
public DaoFactory(){
File root = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath()+File.separator+"lzy");
if (!root.exists()){
root.mkdirs();
}
File dbFile = new File(root,"run.db");
mDatabase = SQLiteDatabase.openOrCreateDatabase(dbFile,null);
}
public static DaoFactory getInstance(){
if (mDaoFactory == null){
synchronized (DaoFactory.class){
if (mDaoFactory == null){
mDaoFactory = new DaoFactory();
}
}
}
return mDaoFactory;
}
public <T> IDaoInf<T> getDao(Class<T> clazz){
IDaoInf<T> daoInf = new LzyDao<T>();
daoInf.init(mDatabase,clazz);
return daoInf;
}
}
在使用LzyDao之前先封装一些工具类:①获得类的名字,比如person。②数据库操作的时候根据类型进行转换。③查询数据:cursor.getInt();将int第一个字符进行转换成大写
public class DaoUtil {
private DaoUtil() {
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 获得类名
*/
public static String getTableName(Class<?> clazz) {
return clazz.getSimpleName();
}
/**
* 数据库操作的时候根据类型进行转换
*/
public static String getColumnType(String type) {
String value = null;
if (type.contains("String")) {
value = " text";
} else if (type.contains("int")) {
value = " integer";
} else if (type.contains("boolean")) {
value = " boolean";
} else if (type.contains("float")) {
value = " float";
} else if (type.contains("double")) {
value = " double";
} else if (type.contains("char")) {
value = " varchar";
} else if (type.contains("long")) {
value = " long";
}
return value;
}
/**
* 查询数据:cursor.getInt();将int第一个字符进行转换成大写
*/
public static String capitalize(String string) {
if (!TextUtils.isEmpty(string)) {
return string.substring(0, 1).toUpperCase(Locale.US) + string.substring(1);
}
return string == null ? null : "";
}
}
LzyDao代码:
public class LzyDao<T> implements IDaoInf<T>{
// SQLiteDatabase
private SQLiteDatabase mSqLiteDatabase;
// 泛型类
private Class<T> mClazz;
private static final Object[] mPutMethodArgs = new Object[2];
private static final Map<String, Method> mPutMethods
= new ArrayMap<>();
@Override
public void init(SQLiteDatabase sqLiteDatabase,Class<T> clazz) {
this.mSqLiteDatabase = sqLiteDatabase;
this.mClazz = clazz;
// 创建表sql
/*"create table if not exists Person ("
+ "id integer primary key autoincrement, "
+ "name text, "
+ "age integer, "
+ "flag boolean)";*/
StringBuffer sb = new StringBuffer();
sb.append("create table if not exists ")
.append(DaoUtil.getTableName(mClazz))
.append("(id integer primary key autoincrement, ");
Field[] fields = mClazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);// 设置权限
String name = field.getName();
String type = field.getType().getSimpleName();// int String boolean
// type需要进行转换 int --> integer, String text;
sb.append(name).append(DaoUtil.getColumnType(type)).append(", ");
}
sb.replace(sb.length() - 2, sb.length(), ")");
String createTableSql = sb.toString();
// 创建表
mSqLiteDatabase.execSQL(createTableSql);
}
@Override
public int insert(T t) {
ContentValues values = CreateContentValues(t);
return (int) mSqLiteDatabase
.insert(DaoUtil.getTableName(mClazz),
null,values);
}
@Override
public void insert(List<T> data) {
mSqLiteDatabase.beginTransaction();
for (T d:data) {
insert(d);
}
mSqLiteDatabase.setTransactionSuccessful();
mSqLiteDatabase.endTransaction();
}
@Override
public int delete(T t) {
return 0;
}
@Override
public List<T> queryAll() {
return null;
}
private ContentValues CreateContentValues(T t) {
ContentValues values = new ContentValues();
Field [] fields = mClazz.getDeclaredFields();
for (Field f : fields) {
try {
//私有和公有都可以访问
f.setAccessible(true);
String key = f.getName();
Object value = f.get(t);
mPutMethodArgs[0] = key;
mPutMethodArgs[1] = value;
// 方法使用反射 , 反射在一定程度上会影响性能
//参考AppCompatViewinflater源码
String filedTypeName = f.getType().getName();
// 还是使用反射 获取方法 put 缓存方法
Method putMethod = mPutMethods.get(filedTypeName);
if (putMethod == null) {
putMethod = ContentValues.class.getDeclaredMethod("put",
String.class, value.getClass());
mPutMethods.put(filedTypeName, putMethod);
}
// 通过反射执行
putMethod.invoke(values, mPutMethodArgs);
/* Method putMethod = ContentValues.class
.getDeclaredMethod("put",
String.class,value.getClass());
//通过反射执行
putMethod.invoke(values,key,value);*/
} catch (Exception e) {
e.printStackTrace();
}finally {
mPutMethodArgs[0] = null;
mPutMethodArgs[1] = null;
}
}
return values;
}
}