🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 数据库初始化 DemoApplication累承担了DaoSession的初始化工作 ~~~ public class DemoApplication extends Application { public static final boolean ENCRYPTED = false; private static DemoApplication youAppction; private DaoSession daoSession; @Override public void onCreate() { super.onCreate(); DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, ENCRYPTED ? "notes-db-encrypted" : "notes-db3"); Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb(); daoSession = new DaoMaster(db).newSession(); } public static DemoApplication getInstance() { return youAppction; } public DaoSession getDaoSession() { return daoSession; } } ~~~ # 以登录模块为例,讲解GreenDao的用法 ~~~ UserDao noteDao=((DemoApplication)getApplication()).getDaoSession().getUserDao() if(noteDao.queryBuilder().where(UserDao.Properties.Password.eq(password),UserDao.Properties.Username.eq(username)).count()>0){ Log.i("登录成功","ok"); Toast.makeText(getApplicationContext(),"登录成功!",Toast.LENGTH_LONG).show(); Constant.Account account= Constant.getAccount(); account.setPhone(username); account.setPassword(password); startActivity(new Intent(LoginActivity.this,MainActivity.class)); }else { Log.i("登录失败","密码错误"); Toast.makeText(getApplicationContext(),"登录失败!账号密码错误",Toast.LENGTH_LONG).show(); } ~~~ 这段代码讲的是 如果 userdao对象,在数据库查询不到结果,就说明输入的账号密码信息错误,从而提示登录失败、密码错误的信息。 第一步先创建UserDao 对象 `UserDao noteDao=((DemoApplication)getApplication()).getDaoSession().getUserDao() ` 第二步再编写数据库查询语句 ~~~ noteDao.queryBuilder().where(UserDao.Properties.Password.eq(password),UserDao.Properties.Username.eq(username)).count() ~~~ count为0,说明输入的账号密码插叙匹配不到数据,count不为0,则说明账号密码正确。 # 以注册模块为例,讲解GreenDao的插入用法 ~~~ User user=new User(); user.setUsername(username); user.setPassword(password); try { noteDao.insert(user); Log.i("注册成功","ok"); Toast.makeText(getApplicationContext(),"注册成功!",Toast.LENGTH_LONG).show(); Constant.Account account= Constant.getAccount(); account.setPhone(username); account.setPassword(password); startActivity(new Intent(LoginActivity.this,MainActivity.class)); }catch (Exception e){ Log.i("注册失败","手机号已存在"); Toast.makeText(getApplicationContext(),"注册失败!手机号已存在",Toast.LENGTH_LONG).show(); Log.e("注册失败信息",e.toString()); } ~~~ 首先想明白自己要插入什么:User对象,因此第一步是先创建User对象 ~~~ User user=new User(); user.setUsername(username); user.setPassword(password); ~~~ 其次使用userdao对象,插入user对象,插入的过程不一定会成功,失败会抛出异常,因此我们使用try{}cath语句进行拦截异常。 插入成功,给予注册成功的提示,插入失败,给予注册失败的提示即可。