老司机带你学习GreenDao3

我知道你们没有图是不会进来的,就是简单的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

喜欢的盆友麻烦点个赞 非常感谢了。。。。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值