Search code examples
androidkotlintype-conversionandroid-edittextnumber-formatting

NumberFormatException for input string Edittext


var bmi: Float
if(binding.rbMetric.isChecked){
    bmi = binding.currWeightEdit.text.toString().toFloat() / binding.meterEditText.toString().toFloat().pow(2)
}else{
    bmi = (binding.currWeightEdit.text.toString().toFloat()*703)/ (binding.feetEditText.text.toString().toInt()*12 + binding.inchesEditText.toString().toInt()).toFloat().pow(2)
}
return bmi

This code is meant to calculate the BMI for either the metric or imperial unit. The input type of the Editexts weight and meter are numberDecimal and meter,feet are number. The error is: java.lang.NumberFormatException: For input string: "com.google.android.material.textfield.TextInputEditText{b7d8c80 VFED..CL. ........ 0,0-385,153 #7f0800cc app:id/inches_edit_text aid=1073741832}". How can I fix this?


Solution

  • On the first calculation you used

    binding.meterEditText.toString().toFloat().pow(2)
    

    when it should have been

    binding.meterEditText.text.toString().toFloat().pow(2)
    

    So it was calling toString() on the EditText view itself. You repeated this error further down where you used toInt().

    To make this code less repetitive and error prone, you could use an extension. Also, when using binding over and over, it's cleaner to use with(binding).

    val TextView.textAsFloat: Float get() = text.toString().toFloat()
    
    return with(binding) {
        if (rbMetric.isChecked) {
            currWeightEdit.textAsFloat / meterEditText.textAsFloat.pow(2)
        } else {
            currWeightEdit.textAsFloat * 703 / (feetEditText.textAsFloat * 12 + inchesEditText.textAsFloat).pow(2)
        }
    }