gradle
// In your root build.gradle file:
buildscript {
repositories {
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}
// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
dependencies {
compile 'org.greenrobot:greendao:3.2.2' // add library
}
// In the build.gradle file of your app project:
android {
...
}
greendao {
schemaVersion 1
daoPackage 'com.test.test.gen'
targetGenDir 'src/main/java'
}
DaoManager
public class DaoManager {
private static final String TAG = DaoManager.class.getSimpleName();
private static final String DB_NAME = "greendaotest";
private Context context;
//多線程中要被共享的使用volatile關鍵字修飾
private volatile static DaoManager manager = new DaoManager();
private static DaoMaster sDaoMaster;
private static DaoMaster.DevOpenHelper sHelper;
private static DaoSession sDaoSession;
/**
* 單例模式獲得操作數(shù)據(jù)庫對象
* @return
*/
public static DaoManager getInstance(){
return manager;
}
public void init(Context context){
this.context = context;
}
/**
* 判斷是否有存在數(shù)據(jù)庫韭山,如果沒有則創(chuàng)建
* @return
*/
public DaoMaster getDaoMaster(){
if(sDaoMaster == null) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
sDaoMaster = new DaoMaster(helper.getWritableDatabase());
}
return sDaoMaster;
}
/**
* 完成對數(shù)據(jù)庫的添加辈挂、刪除斋枢、修改桌肴、查詢操作,僅僅是一個接口
* @return
*/
public DaoSession getDaoSession(){
if(sDaoSession == null){
if(sDaoMaster == null){
sDaoMaster = getDaoMaster();
}
sDaoSession = sDaoMaster.newSession();
}
return sDaoSession;
}
/**
* 打開輸出日志署尤,默認關閉
*/
public void setDebug(){
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
/**
* 關閉所有的操作胃碾,數(shù)據(jù)庫開啟后易稠,使用完畢要關閉
*/
public void closeConnection(){
closeHelper();
closeDaoSession();
}
public void closeHelper(){
if(sHelper != null){
sHelper.close();
sHelper = null;
}
}
public void closeDaoSession(){
if(sDaoSession != null){
sDaoSession.clear();
sDaoSession = null;
}
}
}