我正在将Kotlin与android一起使用,但出现此错误。
原因:java.lang.ClassCastException:java.lang.Float不能为 在第60行中强制转换为java.lang.String
我不明白为什么它以为有一个Float
。这是第60行:
val bal:String = sp.getString("Balance", "0.00")!!.toString()
其中sp是SharedPreferences
的实例。
这是我的完整代码:
package com.applications.darshan.piggybank
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.content.SharedPreferences
import android.view.View
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
private var balance : TextView ?= null
private var amount : EditText ?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
balance = findViewById(R.id.balance)
amount = findViewById(R.id.amount)
var sp:SharedPreferences = this.getSharedPreferences("Balance", 0)
addZero()
balance!!.text = "Your balance is $" + sp.getString("Balance", "0.00")
}
fun onClick(v: View){
var addAmount:Float ?
try{
addAmount = amount!!.text.toString().toFloat()
}catch(e:Exception){
addAmount = 0.00f
}
var sp:SharedPreferences = this.getSharedPreferences("Balance", 0)
val editor = sp.edit()
var amountNum = sp.getString("Balance", "0.00").toFloat()
when(v.id.toString()){
"2131165209" -> amountNum += addAmount!!
"2131165314" -> amountNum -= addAmount!!
}
editor.putString("Balance", amountNum.toString())
editor.apply()
editor.commit()
addZero()
balance!!.text = "Your balance is $" + sp.getString("Balance", "0.00")
}
fun clearBalance(v:View){
var sp:SharedPreferences = this.getSharedPreferences("Balance", 0)
val editor = sp.edit()
editor.putString("Balance", "0.00")
editor.apply()
editor.commit()
addZero()
balance!!.text = "Your balance is $" + sp.getString("Balance", "0.00")
addZero()
}
fun addZero(){
val sp:SharedPreferences = this.getSharedPreferences("Balance", 0)
val bal:String = sp.getString("Balance", "0.00")!!.toString()
val editor = sp.edit()
val balLen = bal.length
val dot:Char = bal[balLen-2]
if(dot.equals('.')){
System.out.println(true)
var x:String = bal + "0"
editor.putString("Balance", x)
System.out.println(x)
editor.apply()
editor.commit()
}
}
}
答案 0 :(得分:0)
尝试从sp中获取一个浮点数,然后将其转换为String
val bal:String = Float.toString(sp.getFloat("Balance", 0.0f));
答案 1 :(得分:0)
您可以像下面这样使用,它将在Float
中键入Cast
Float.valueOf(sp.getString("Balance", "0.00"));