我尝试使用SharedPreferences,但它只会保存最后一个值。
主要活动
mypreference.setPrice(txtPrice.text.toString().toFloat())
mypreference.setSABV(txtABV.text.toString().toFloat())
SharedPreference
class myPreferences(context: Context){
val PREFERENCENAME = "BeerNote"
val PRICE = 0.0f
val ALCOHOLBYVOLUME = 0.0f
val preference = context.getSharedPreferences(PREFERENCENAME,Context.MODE_PRIVATE)
fun setPrice(price:Float){
preference.edit().putFloat(PRICE.toString(),price).apply()
}
fun getPrice():Float{
return preference.getFloat(PRICE.toString(),0.0f)
}
fun setSABV(abv:Float){
preference.edit().putFloat(ALCOHOLBYVOLUME.toString(),abv).apply()
}
fun getABV():Float{
return preference.getFloat(ALCOHOLBYVOLUME.toString(),0.0f )
}
}
当我尝试恢复数据时
Toast.makeText(this, "Price:"+mypreference.getPrice(), Toast.LENGTH_LONG).show()
Toast.makeText(this, "ABV:"+mypreference.getABV(), Toast.LENGTH_LONG).show()
仅在价格和ABV中保存ABV值
答案 0 :(得分:-1)
您应该使用常量字符串作为键,而不是像现在那样将浮点数转换为字符串。看起来像:
class myPreferences(context: Context){
val PREFERENCENAME = "BeerNote"
val PRICE = 0.0f
val ALCOHOLBYVOLUME = 0.0f
val priceKey = "price"
val SABVKey = "sabv"
val preference = context.getSharedPreferences(PREFERENCENAME,Context.MODE_PRIVATE)
fun setPrice(price:Float){
preference.edit().putFloat(priceKey,price).apply()
}
fun getPrice():Float{
return preference.getFloat(priceKey,0.0f)
}
fun setSABV(abv:Float){
preference.edit().putFloat(SABVKey,abv).apply()
}
fun getABV():Float{
return preference.getFloat(SABVKey,0.0f )
}
}