Android Studio中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
相关产品推荐
相关产品推荐

