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

Android SharedPreference存取值不一致问题排查求助

问题分析与解决

问题出在重复创建SharedPreferences.Editor实例上:

  • 你第一次调用sharedPref.edit()生成了一个Editor,调用putString添加了要保存的数据,但没有立刻提交这个Editor
  • 第二次调用sharedPref.edit()又生成了一个全新的空Editor,此时调用commit()等于什么都没保存
  • 最后读取时因为没有有效数据,所以返回了你设置的默认值"asdf"

修正后的代码可以这样写:

val sharedPref = getSharedPreferences("Data", Context.MODE_PRIVATE)
val inputValue = binding.text.editText?.text.toString()
// 创建一次Editor,链式调用完成存值和提交
sharedPref.edit()
    .putString("Str", inputValue)
    .commit()
print("Value: ")
println(inputValue)
println(sharedPref.getString("Str","asdf"))

或者也可以先把Editor对象存起来,分步操作:

val sharedPref = getSharedPreferences("Data", Context.MODE_PRIVATE)
val editor = sharedPref.edit()
val inputValue = binding.text.editText?.text.toString()
editor.putString("Str", inputValue)
print("Value: ")
println(inputValue)
editor.commit()
println(sharedPref.getString("Str","asdf"))

核心就是确保同一个Editor实例完成put操作和commit操作,这样输入的值才能正确保存到SharedPreferences中,读取时就能得到预期的结果了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:50:18