我知道你們沒有圖是不會進來的,就是簡單的greenDao3的增刪改查 和完全自動化升級字段且保留之前的數據!
IMG_0049.JPG
- 步驟
- 1.依賴 首先在project項目中的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' //這個是黃油刀的注解
// 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 //版本號,升級時可配置
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.然后可以新建一個實體類 然后點擊工具欄中的build-----make project 會自動生成相應的dao類
@Entity
public class Test {
@Id
private Long id;
private int url;
private String name;
private String desc;
}
- 切記 id一定是long型的 不然插入數據的時候會報錯的
- 4.升級不刪除老數據
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");
//完全自動升級本地數據庫 要升級那個bean 只需要調用下面這個方法
// MigrationHelper.getInstance().migrate(db, xxx.class);
MigrationHelper.getInstance().migrate(db, TestDao.class);
}
}
上面圖 我是升級了一個desc的字段 發現之前的數據依舊保存 記得 要添加某個實體的字段 schemaVersion 一定要大于當前版本 也就說當前版本是6 那么升級的需 要設置為7 才會有保存之前數據的作用 大家可以多試幾次.
-
5.具體使用方法可以看代碼了。代碼才是最好的老師
下面是Demo地址
https://github.com/liuwen370494581/greenDao3