Android Studio使用GreenDao笔记

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

一、在项目的build.gradle的depedencies中添加classpath 'org.greenrobot:greendao-gradle-plugin:3.1.1'

dependencies {
    classpath 'com.android.tools.build:gradle:2.1.2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    classpath 'org.greenrobot:greendao-gradle-plugin:3.1.1'
 }

二、在app的build.gradle中添加

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'//添加此处

android {
   ...
    //添加此处
    greendao {
        schemaVersion 1
        daoPackage '[your package path].dao.gen'
        targetGenDir 'src/main/java'
    }
}

dependencies {
    ...
    //添加此处
    compile 'org.greenrobot:greendao:3.1.1'
    compile 'org.greenrobot:greendao-generator:3.1.0'
}

三、在实体类中使用

@Entity
public class User {

    @Id(autoincrement = true)
    private Long id;
    @Property
    private String userName;
    @Property
    private String userPassword;
}

四、选择菜单栏里的Build》Make Project会生成DaoMasterDaoSessionUserDao等文件

五、编写GreenDao的工具类

public class GreenDaoUtil {

    private DaoMaster master;
    private DaoMaster.DevOpenHelper openHelper;
    private DaoSession session;
    private SQLiteDatabase db;

    private static GreenDaoUtil instance;

    public static GreenDaoUtil getInstance() {
        if (instance == null) {
            instance = new GreenDaoUtil();
        }
        return instance;
    }

    private void initGreenDao(Context context) {
        openHelper = new DaoMaster.DevOpenHelper(context, "[your database name]", null);
        db = openHelper.getWritableDatabase();
        master = new DaoMaster(db);
        session = master.newSession();
    }

    public DaoSession getSession(Context context) {
        if (master == null) {
            initGreenDao(context);
        }
        return session;
    }

    public SQLiteDatabase getDb(Context context) {
        if (db == null) {
            initGreenDao(context);
        }
        return db;
    }
}

转载于:https://my.oschina.net/yuewawa/blog/754834

你可能感兴趣的:(java,移动开发,python)