You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SharedPreferences登录存储异常求助:存入后无法读取值

问题分析与解决方案

嘿,我一眼就瞅出你代码里的问题啦!

核心问题

你每次调用sharedPreferences.edit()时,都会生成一个全新的SharedPreferences.Editor实例。前面三次putString、putBoolean操作分别在三个不同的Editor对象上执行,最后调用commit()的却是第四个空的Editor——等于啥修改都没提交,自然后续读取时拿不到值。

修正后的代码

你需要复用同一个Editor对象,把所有修改操作都放在同一个实例上,最后再统一提交:

CheckBox checkBoxRememberMe = (CheckBox) findViewById(R.id.checkBoxRememberLogin);
if(checkBoxRememberMe.isChecked()){
    // 只创建一次Editor实例,复用它完成所有修改
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("EMAIL", email);
    editor.putString("PASSWORD", password);
    editor.putBoolean("REMEMBERLOGIN", true);
    // 一次性提交所有修改
    editor.commit();

    user = sharedPreferences.getString("EMAIL", "");
    passw = sharedPreferences.getString("PASSWORD", "");
    System.out.println("---------------" + email + "-----" + password + "-----------");
    System.out.println("---------------" + user + "-----" + passw + "------------");
}
finish();

额外小提示

如果不需要立即判断提交是否成功(比如不用commit()的返回值做逻辑),推荐用editor.apply()替代commit()——它是异步提交到磁盘,不会阻塞主线程,性能会更友好~

内容的提问来源于stack exchange,提问作者Knoll Luki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:26:06