首先说一下数据库 数据库适用于缓存
第一步 万年不变的 导依赖
//GreenDao数据库*****************
implementation'org.greenrobot:greendao:3.2.2' //依赖库
在我们的根目录下导入的和我们的gradle导一起
classpath'org.greenrobot:greendao-gradle-plugin:3.2.1'//GreenDao
// apply 插件 和转义同级***************
applyplugin:'org.greenrobot.greendao'
定义我们的路径
greendao {
schemaVersion1
daoPackage'yxx.com.greendao'
targetGenDir'src/main/java'
}
接下来就是我们的App类了
@Override
public void onCreate() {
super.onCreate();
DaoMaster.DevOpenHelper helper =new DaoMaster.DevOpenHelper(this,"aserbao",null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster =new DaoMaster(db);
daoSession = daoMaster.newSession();
}
private static DaoSessiondaoSession;
public static DaoSession getDaoSession() {
return daoSession;
}
最后简单的实现以下效果
我们自己定义了几个点击事件来测试
public void onViewClicked(View view) {
studentDao = GreenD.getDaoSession().getStudentDao();
switch (view.getId()) {
case R.id.add:
//增加数据
for (int i =0; i <10; i++) {
Student user =new Student();
// user.setId(0+i);
user.setName("张三" + i);
studentDao.insert(user);
String s = user.getName().toString();
Log.e("myMessage",""+s);
}
break;
case R.id.query:
//查询数据
List userList =studentDao.loadAll();
StringBuilder sb =new StringBuilder();
for (int i =0; i < userList.size(); i++) {
Student user = userList.get(i);
String userInfo = user.toString();
sb.append(userInfo +"------");
}
//查询到数据设置到TextView
String queryAllInfo = sb.toString();
//text.setText(queryAllInfo);
Log.e("myMessage",""+queryAllInfo);
break;
case R.id.delete:
Student user =new Student();
String s = user.toString();
studentDao.deleteAll();
Log.e("myMessage",""+s);
break;
case R.id.updata:
cusomeruser =new Student();
cusomeruser.setId((long)1);
cusomeruser.setName("拉拉啦");
studentDao.update(cusomeruser);
String s1 =cusomeruser.toString();
Log.e("myMessage",""+s1);
break;
}
}