GreenDao配置依賴
工程配置:添加插件 更好支持GreenDao
buildscript {
repositories {
jcenter()
mavenCentral() // 添加的代碼
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}
項(xiàng)目配置:添加插件
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
項(xiàng)目配置:添加依賴
dependencies {
//greendao
implementation 'org.greenrobot:greendao:3.2.2' // add library
}
初始化GreenDao配置
greendao{
schemaVersion 1 //數(shù)據(jù)庫版本號
daoPackage 'com.example.lizhengjun.dao' //數(shù)據(jù)庫全路徑
targetGenDir 'src/main/java' //存放位置
}
schemaVersion--> 指定數(shù)據(jù)庫schema版本號,遷移等操作會用到;
daoPackage --> dao的包名,包名默認(rèn)是entity所在的包;
targetGenDir --> 生成數(shù)據(jù)庫
- 配置文件中的設(shè)置
- 設(shè)置Green中的DaoMaster/DaoSession/實(shí)體類Dao生成路徑
- 設(shè)置實(shí)體類
@Entity
public class Student {
@Id(autoincrement = true)
private Long id;
@Property
@NotNull
private String name;
@Property
private int age;
}
文件生成:Build - > ReBuild Project
在Application類中完成內(nèi)容配置(或者使用工具類)
Application有自己的生命周期,OnCreate方法必須首先被調(diào)用
①本類對象的獲取
②DaoMaster、DaoSession對象的獲取
③提供方法,獲取DaoSession對象
創(chuàng)建一個類 繼承Application
(注意:這里繼承Application 需在清單文件中注冊(不然會報空指針異常))
- 獲取實(shí)體類Dao對象
XXXDao xxxdao = App.getInstance().getDaoSession().getXXXDao();
xxxdao.增刪改查();
出處。
GreenDao判斷數(shù)據(jù)庫中是否存在
private boolean isHased(CollectionDbBean collectionDbBean) {
List<CollectionDbBean> list = collectionDbBeanDao.queryBuilder()
.where(CollectionDbBeanDao.Properties.Title.eq(collectionDbBean.getTitle())).list();
if (list.size() > 0) {
return true;
} else {
return false;
}
}
懶加載
//如果用戶可見加載數(shù)據(jù),不可見清空
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
initData();
} else {
if (datas != null && datas.size() > 0) {
datas.clear();
}
}
}