SharedPreferences仅保存最后一个值

问题描述 投票:-2回答:1

我尝试使用SharedPreferences,但仅保存最后一个值。

MainActivity

myPreferences.setPrice(txtPrice.text.toString().toFloat())
myPreferences.setSABV(txtABV.text.toString().toFloat())

SharedPreferences处理程序:

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值保存在Price和ABV中。

android kotlin sharedpreferences
1个回答
-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 )
}
}
© www.soinside.com 2019 - 2024. All rights reserved.