在 sharedpreferences 中存储多个 int 键值时出现问题,有什么解决方案吗?

Problem when stored more than one int key values in sharedpreferences, any solutions?

我尝试在 Kotlin 中保存 EditText 的背景颜色和文本颜色。我的意思是:

private lateinit var sharedpreferences: SharedPreferences
val bgColorKey=0
val textColorKey=0

//SAVING CODE:
val editor = sharedpreferences.edit()
editor.putInt(bgColorKey.toString(), R.drawable.col1)
editor.putInt(textcolorKey.toString(), R.color.white)
editor.commit()

//PRINT LINE CODE:
println("NEW bgColorKey = "+sharedpreferences.getInt(bgColorKey.toString(), 0))  // I/System.out: NEW bgColorKey = 2130968609
println("NEW textcolorKey = "+sharedpreferences2.getInt(textcolorKey.toString(), 0))  // I/System.out: NEW textcolorKey = 2130968609

当我使用 putInt() 方法在每个键中存储不同的颜色资源 ID 时,它们都取最后一个值,即两个键的值都是 R.drawable.whitebackground

这是一个错误吗?还是我做错了什么?

这里,

val bgColorKey = 0
val textColorKey = 0

这些密钥相同(均为 0)。

在你的代码中。第二个 putInt() 将替换第一个键值对,因为它们具有相同的键。每个键应该不同。例如,

val bgColorKey = 0
val textColorKey = 1

而且因为键需要是字符串。比较好用,

val bgColorKey = "bgColorKey"
val textColorKey = "textColorKey"

因为这使代码更易于阅读。

为了存储不同的值,您必须使用不同的键。

试试这个:

private lateinit var sharedpreferences: SharedPreferences
val bgColorKey = "bgColor"        //key must be a `String` type, required by SharedPreference
val textColorKey= "textColor"     //different thing, diffrent key, they're must be separated

//SAVING CODE:
val editor = sharedpreferences.edit()
editor.putInt(bgColorKey, R.drawable.col1)    //the value you store is a resource id, Int type
editor.putInt(textColorKey, R.color.white)
editor.commit()

//PRINT LINE CODE:
println("bgColorKey value = "+sharedpreferences.getInt(bgColorKey, 0))  
println("textColorKey value = "+sharedpreferences2.getInt(textColorKey, 0))

其他答案没有指出,但是这个:

val bgColorKey=0

//...

bgColorKey.toString()

return 不是 "bgColorKey" 的字符串键。它正在将 0 转换为值为 "0" 的字符串。由于您定义的两个键都基于整数 0,因此它们都创建相同的键 "0".

键应该是唯一的字符串。所以像这样:

val bgColorKey = "BG_COLOR_KEY"
val textColorKey = "TEXT_COLOR_KEY"