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

Android Studio中SharedPreferences始终返回默认值问题求助

问题解决:SharedPreferences存储后无法读取值的原因

你遇到的问题根源是存储SharedPreferences时,所有key的末尾都多了一个逗号,导致读取时使用的key和存储的key不匹配,最终只能返回默认值。

错误代码位置

在登录成功后的存储逻辑里,你写的是:

editor.putString("logged,", "true");
editor.putString("name,", name);
editor.putString("email,", email);
editor.putString("apiKey,", apiKey);

这里的key是"logged,"、"name,"这类带逗号的字符串,但你读取时用的是不带逗号的key(比如sharedPreferences.getString("logged","false")),两者完全不匹配,自然读不到存储的值。

修改后的代码

把所有key后面的逗号去掉即可:

if(status.equals("success")){
    name = jsonObject.getString("name");
    email = jsonObject.getString("email");
    apiKey = jsonObject.getString("apiKey");
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("logged", "true");
    editor.putString("name", name);
    editor.putString("email", email);
    editor.putString("apiKey", apiKey);
    editor.apply();
    Intent intentMain = new Intent(getApplicationContext(), MainActivity.class);
    startActivity(intentMain);
    finish();
}

补充说明

SharedPreferences的key是严格区分字符串内容的,哪怕只是多一个标点符号,都会被视为不同的key。你存储时用了带逗号的key,读取时用正确的key自然找不到对应数据,只能返回你设置的默认值"false"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:58:09