使用Paper库的Android记住登录复选框功能异常求助
搞定你的「记住我」自动登录异常问题
嘿,我仔细扒了你的代码,找到了几个导致“未主动登出却自动登录”的核心问题,咱们一步步来修复:
1. Paper存储键名搞混了(最致命的错误)
在LoginActivity的allowAccessToUser方法里,你两次用了同一个键Prevalent.userPassKey来存手机号和密码——这直接导致手机号被密码覆盖,而且如果之前用户勾选过记住我,旧的存储数据没清除,下次启动APP还是会读到数据自动登录。
错误代码片段:
if(checkBox.isChecked()){ Paper.book().write(Prevalent.userPassKey, phone); // 错把手机号存到密码的键里了 Paper.book().write(Prevalent.userPassKey, password); // 再次覆盖,Paper里只剩密码 }
修复后代码:
if(checkBox.isChecked()){ Paper.book().write(Prevalent.userPhoneKey, phone); // 用对应键存手机号 Paper.book().write(Prevalent.userPassKey, password); // 用对应键存密码 }
2. MainActivity里的字符串判断写错了
你用phone!="" && password!=""来判断是否有存储的账号,这在Java里是典型错误——!=比较的是字符串对象的引用而非内容,而且如果Paper没读到数据,phone会是null,直接这么写会触发空指针异常。
错误代码片段:
if (phone!="" && password!=""){
改成安全的判断逻辑:
String phone = Paper.book().read(Prevalent.userPhoneKey); String password = Paper.book().read(Prevalent.userPassKey); // 先判断非null,再判断内容不为空 if (phone != null && password != null && !TextUtils.isEmpty(phone) && !TextUtils.isEmpty(password)){ allowAccess(phone, password); // 剩下的loadingDialog逻辑不变 }
3. 缺了登出时清除存储的逻辑
你提到的“未主动登出却自动登录”,大概率是因为用户登出时,你没把Paper里存的账号密码删掉,导致下次打开APP依然读取到旧数据自动登录。
给你的登出功能(比如HomeActivity的登出按钮点击事件)加上这段代码:
// 清除Paper里的账号密码存储 Paper.book().delete(Prevalent.userPhoneKey); Paper.book().delete(Prevalent.userPassKey); // 或者直接清空整个存储:Paper.book().destroy(); // 跳回登录页并清空栈内其他页面,避免返回回到首页 Intent intent = new Intent(HomeActivity.this, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish();
额外的小优化建议
- 延迟存储时机:现在你是在查询数据库之前就存储数据,万一密码错误也会存无用信息,建议改成验证成功后再存储:
// 在LoginActivity的验证成功分支里 if(userData.getPassword().equals(password)){ Toast.makeText(LoginActivity.this, "Logged in successfully!", Toast.LENGTH_SHORT).show(); loadingDialog.dismiss(); // 验证成功才存储账号信息 if(checkBox.isChecked()){ Paper.book().write(Prevalent.userPhoneKey, phone); Paper.book().write(Prevalent.userPassKey, password); } Intent intent = new Intent(LoginActivity.this, HomeActivity.class); startActivity(intent); }
- 改用一次性数据库查询:
MainActivity的allowAccess里用了addValueEventListener,这个会持续监听数据库变化,自动登录只需要一次查询即可,换成addListenerForSingleValueEvent更节省资源:
myRef.addListenerForSingleValueEvent(new ValueEventListener() { // 原有的onDataChange和onCancelled逻辑不变 });
内容的提问来源于stack exchange,提问作者RafiaChy
相关产品推荐
相关产品推荐

