安卓中对SQLite的操作,如果不借助工具类的话很容易出错,比如SQL语句不规范(少个空格是很经常的事),而借助一些工具类能很明显的提升编程效率。GreenDao是一个很好的开源工具。用法如下:
1.在eclipse下新建一个java project,在项目中新建名为lib的package,在lib中导入两个jar包:freemarker.jar和greendao-generator-2.0.0.jar(先复制到lib目录下,然后右键lib,选择build path-->configure build path,在libraries一栏点击add jars,选择拷贝好的两个jar包点击ok)
2.在项目下新建测试类:GreenDaoTest,写入如下代码:
import java.io.IOException;
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;
public class GreenDaoTest {
public static void main(String[] args) {
Schema schema=new Schema(1,"com.example.ygd.jreduch08");
addUser(schema);
try {
new DaoGenerator().generateAll(schema, "D:\\GreenDaoSrc"); //创建任意文件夹并将文件夹位置写到这
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addUser(Schema schema){
Entity entity=schema.addEntity("User"); //实体类的java文件
entity.setTableName("user"); //表名
entity.addIdProperty().primaryKey().autoincrement();
entity.addStringProperty("name"); //属性
entity.addStringProperty("pwd");
entity.addStringProperty("age");
entity.addStringProperty("imgUrl");
}
}
运行该程序,得到如下结果:
![这里写图片描述](https://img-blog.csdn.net/20160428155305614)
在刚才新建的文件夹下找到建好的四个文件,复制到android studio
的dao目录下(没有则新建)
然后,在android studio中导包,先拷到libs目录下,在点击添加依赖项,选择第二项 File Dependency。导完如下图:
![这里写图片描述](https://img-blog.csdn.net/20160428164951371)
在Activity中调用:
userDao= MyApplication.getInstance().getDaoSession(this).getUserDao();
然后重写application,新建一个application的包,然后在下面新建一个MyApplication.class,代码如下:
package com.example.ygd.jreduch08.application;
import android.app.Application;
import android.content.Context;
import com.example.ygd.jreduch08.dao.DaoMaster;
import com.example.ygd.jreduch08.dao.DaoSession;
public class MyApplication extends Application {
private DaoSession daoSession;
private DaoMaster daoMaster;
//Application实例对象
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance=this;
}
public static MyApplication getInstance(){
return instance;
}
public DaoMaster getDaoMaster(Context context){
if(daoMaster==null){
DaoMaster.OpenHelper helper=new DaoMaster.DevOpenHelper(context,"MyDbTest.db",null);
daoMaster=new DaoMaster(helper.getWritableDatabase());
}
return daoMaster;
}
public DaoSession getDaoSession(Context context){
if(daoSession==null){
if(daoSession==null){
daoMaster=getDaoMaster(context);
}
daoSession=daoMaster.newSession();
}
return daoSession;
}
}
在清单文件中将application的名字设置为刚才重写的方法。
然后就可以使用GreenDao提供的各种工具了。
(如果要升级数据库的话,也是要在eclipse中操作,重新生成那四个文件,然后再拷贝过去)