我知道你們沒有圖是不會(huì)進(jìn)來的,就是簡(jiǎn)單的greenDao3的增刪改查 和完全自動(dòng)化升級(jí)字段且保留之前的數(shù)據(jù)杀狡!
IMG_0049.JPG
- 步驟
- 1.依賴 首先在project項(xiàng)目中的build.gradle 中添加如下代碼
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0'
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' //這個(gè)是黃油刀的注解
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
- 2.依賴 在modele中的build.gradle 中添加如下代碼
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion 23
buildToolsVersion "25.0.0"
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
//greendao配置
greendao {
schemaVersion 6 //版本號(hào),升級(jí)時(shí)可配置
daoPackage 'star.liuwen.com.endgreendao3.Dao' //包名
targetGenDir 'src/main/java' //生成目錄
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'org.greenrobot:greendao:3.2.0'
}
- 3.然后可以新建一個(gè)實(shí)體類 然后點(diǎn)擊工具欄中的build-----make project 會(huì)自動(dòng)生成相應(yīng)的dao類
@Entity
public class Test {
@Id
private Long id;
private int url;
private String name;
private String desc;
}
- 切記 id一定是long型的 不然插入數(shù)據(jù)的時(shí)候會(huì)報(bào)錯(cuò)的
- 4.升級(jí)不刪除老數(shù)據(jù)
public class MySQLiteOpenHelper extends DaoMaster.OpenHelper {
public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.e("greenDAO",
"Upgrading schema from version " + oldVersion + " to " + newVersion + " by migrating all tables data");
//完全自動(dòng)升級(jí)本地?cái)?shù)據(jù)庫 要升級(jí)那個(gè)bean 只需要調(diào)用下面這個(gè)方法
// MigrationHelper.getInstance().migrate(db, xxx.class);
MigrationHelper.getInstance().migrate(db, TestDao.class);
}
}
上面圖 我是升級(jí)了一個(gè)desc的字段 發(fā)現(xiàn)之前的數(shù)據(jù)依舊保存 記得 要添加某個(gè)實(shí)體的字段 schemaVersion 一定要大于當(dāng)前版本 也就說當(dāng)前版本是6 那么升級(jí)的需 要設(shè)置為7 才會(huì)有保存之前數(shù)據(jù)的作用 大家可以多試幾次.
-
5.具體使用方法可以看代碼了菜谣。代碼才是最好的老師
下面是Demo地址
https://github.com/liuwen370494581/greenDao3