0
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?

0

2 Answers 2

1

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)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Update your code on, you are getting editText input in wrong way.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.