greenDao的使用

  1. 在 Android Studio的build.gradle文件中添加

classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'

编译之后进行下一步

     2.   在 app 文件夹的build.gradle 文件中配置

apply plugin: 'org.greenrobot.greendao'

compile 'org.greenrobot:greendao:3.0.1'

 

设置greenDao的路径:

greendao {

    schemaVersion 1

    daoPackage 'com.demo.db'

    targetGenDir 'src/main/java'

}

     3.  创建实体类

比如user:

@Entity

public class User {

    @Id(autoincrement = true)

    private Long id;

    @NotNull

    @Unique

    @Property(nameInDb = "user_number")

    private String userNumber;

    @NotNull

    @Property(nameInDb = "user_password")

private String userPassword;

}

     4.   点击 锤子 Make Project

greenDao会生成两个实体类对应的dao文件,比如 userDao

以及DaoMaster和DaoSession

     5.  创建对象以及实例化

private DaoMaster.DevOpenHelper mHelper;

private SQLiteDatabase db;

private DaoMaster mDaoMaster;

private DaoSession mDaoSession;

private UserDao mUserDao;

private User mUser;

 

mHelper = new DaoMaster.DevOpenHelper(this, "demo-db", null);

     db = mHelper.getWritableDatabase();

mDaoMaster = new DaoMaster(db);

mDaoSession = mDaoMaster.newSession();

mUserDao = this.getDaoSession().getUserDao();
  添加两个方法:

private DaoSession getDaoSession() {

        return mDaoSession;

    }

 

private SQLiteDatabase getDb() {

        return db;

    }

  6.  插入,查询操作

// greenDao 插入

  mUser = new User((long) 2, "100", "100");

      mUserDao.insertOrReplace(mUser);

// greenDao 查询

   List<User> users = mUserDao.loadAll();

   for (int i = 0; i < users.size(); i++) {

if (users.get(i).getUserNumber().equals(mEtUsername.getText().toString())

&& users.get(i).getUserPassword().equals(mEtPassword.getText().toString())) {

Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show();

startActivity(new Intent(this, IndexActivity.class));

                    }

                }

posted @ 2016-10-20 10:43  Travis1022  阅读(156)  评论(0编辑  收藏  举报