Android快速开发框架GreenDao 3.0.1使用

一、配置Gradle

1、在主目录下的build.gradle中,添加greenDao插件支持
buildscript {
repositories {
mavenCentral()
}
dependencies {
//在原有基础上加上下面这句
classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'
}
}
2、在项目module目录下的build.gradle中添加依赖
apply plugin: 'org.greenrobot.greendao'
dependencies {
compile 'org.greenrobot:greendao:3.0.1'
}
greendao {
schemaVersion 1
//自动生成的文件所在目录
daoPackage 'com.hh.greendao.gen'
targetGenDir 'src/main/java'
}

二、使用GreedDao
1、写实体javaBean
@Entitypublic
class User {
@Id(autoincrement =true)
private Long id;
private String name;
private int age;
private String school;
}
2、配置Application
public class MyApplication extends Application {
private static DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"myapp");
Database db = helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
}
public static DaoSession getDaoSession(){
return daoSession;
}
}

3、在Activity中使用
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv_show)
TextView tv_show;
private UserDao userDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
init();
}
private void init(){
DaoSession daoSession= MyApplication.getDaoSession();
userDao=daoSession.getUserDao();
}

@OnClick({R.id.tv_add,R.id.tv_delete,R.id.tv_query,R.id.tv_update})
public void clickView(View view){
switch (view.getId()){
case R.id.tv_add:
addUser();
break;
case R.id.tv_delete:
deleteUser();
break;
case R.id.tv_update:
updateUser();
break;
case R.id.tv_query:
queryUser();
break;
}
}

private void addUser()
{
User user=new User(null,"hbx",22,"GDUT");
userDao.insert(user);
}

private void deleteUser()
{
userDao.deleteByKey(new Long(2));
}

private void updateUser()
{
User newOne=new User(new Long(3),"hjkdj",89,"zhong");
userDao.update(newOne);
}

private void queryUser()
{
Query query = userDao.queryBuilder().where(UserDao.Properties.Id.eq("3")).build();
List<User> users = query.list();
for (User user:users)
{
tv_show.setText(user.getSchool());
}
}

}

推荐阅读更多精彩内容