Я использую Android с Kotlin, и я получаю эту ошибку.
Причина: java.lang.ClassCastException: java.lang.Float не может быть преобразован в java.lang.Строка в строке 60
Я не понимаю, почемудля начала он думает, что есть 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()
}
}
}