参考链接地址: https://www.jianshu.com/p/b017ca5fe0ab
https://www.cnblogs.com/ssqhan/p/8082690.html
-
配置Gradle
buildscript { repositories { jcenter() mavenCentral() // 添加远程仓库地址 } dependencies { classpath 'com.android.tools.build:gradle:2.3.2' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // 添加插件 更好支持GreenDao } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }
2.配置项目下的build.gradle
apply plugin: ‘com.android.application’
apply plugin: ‘org.greenrobot.greendao’
//apply plugin: ‘android-apt’
android {
compileSdkVersion 26
buildToolsVersion ‘26.0.2’
defaultConfig {
applicationId "cn.gz.demo"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
multiDexEnabled true
flavorDimensions "versionCode"
}
greendao {
//数据库版本号
schemaVersion 1
//例如 包名.greendao
daoPackage 'cn.gz.demo.dao'
targetGenDir 'src/main/java'
}
}
dependencies {
compile fileTree(include: [’*.jar’], dir: ‘libs’)
testCompile ‘junit:junit:4.12’
// 数据库
implementation ‘org.greenrobot:greendao:3.2.2’
}
-
application 里面初始化
public class BaseApplication extends Application {
public static BaseApplication instances;@Override
public void onCreate() {
super.onCreate();//初始化数据库 initDB();
}
private DaoMaster.DevOpenHelper mHelper;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
private SQLiteDatabase db;private void initDB() {
mHelper = new DaoMaster.DevOpenHelper(this, “demo.db”, null);
db = mHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}public static BaseApplication getInstances() {
return instances;
}public DaoSession getDaoSession() {
return mDaoSession;
}public Database getDb() {
return db;
}
}
可是会发现, DAOMaster 是红色的 且出现: cannot resolve symbol ‘daoMaster’
正确姿势就该这样:
1.先建一个实体这样:(直接COPY 官网上的)
@Entity
public class User {
@Id
private Long id;
private String name;
@Transient
private int tempUsageCount; // not persisted
// getters and setters for id and user …
}
什么,又是一片红: 一通 ‘alt+enter’ 解决问题
(2) 这样就自动生成三个文件
我当时现现了另一个神级的错误: 三个文件最上面出现 package; 并且标红
解决方法:直接删除 package
(后来发现,删除是不对的,没有能正确的生成包名是因为 User 实体的位置放置不对,所以生成的 DaoMaster,DaoSession,UserDao 的包名都不正确)
又发现:userDao里的 User又标红 'alt+enter' 直接 import User就可以了!
现在才刚刚开始!