1.在工程project的build.gradle
repositories://添加一个仓库
mavenCentral()
dependencies里边
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
2.在当前module的build.gradle文件里添加依赖
compile 'org.greenrobot:greendao:3.2.2'
3.在当前module的build.gradle文件里和dependencies 并列添加
greendao {
schemaVersion 1 //数据库版本号
daoPackage 'com.example.(你项目的包名).gen' //自 动生成代码的一个位置
targetGenDir 'src/main/java' //自动生成代码的一个位置
}
4.在当前module的build.gradle文件里顶部添加
apply plugin: 'org.greenrobot.greendao'
5.创建实体Bean,再类上要写注解@Entity,I属性@Id,@Property(nameInDb = "属性名")
6.CleanBuild之后会生成gen文件
7.创建MyApplication继承Application(一定要在清单文件中配置name)
MyApplication:
package com.example.greendao; import android.app.Application; import android.database.sqlite.SQLiteDatabase; public class myApplication extends Application { private static myApplication application; private DaoSession daoSession; public static myApplication getApplication(){ return application; } @Override public void onCreate() { super.onCreate(); application=this; createDb(); } private void createDb() { //创建数据库辅助类对象 DaoMaster.DevOpenHelper devOpenHelper=new DaoMaster.DevOpenHelper(this,"greendao.db"); //数据库对象 SQLiteDatabase db=devOpenHelper.getWritableDatabase(); //链接数据库 DaoMaster daoMaster = new DaoMaster(db); daoSession = daoMaster.newSession(); } public DaoSession getDaoSession(){ return daoSession; } }
MainActivity:
package com.example.greendao; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //添加 insertdata(); //查询 query(); } public ShowBeanDao showBeanDao(){ return myApplication.getApplication().getDaoSession().getShowBeanDao(); } //添加 private void insertdata() { ShowBean insertData = new ShowBean(null,"王小二"); showBeanDao().insert(insertData); } //查询 private void query() { ShowBean user = showBeanDao().load((long) 1); Log.i("tag", "结果:" + user.getId() + "," + user.getName()); } }