Reputation: 7
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?
Upvotes: 0
Views: 679
Reputation: 1520
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
Upvotes: 0
Reputation: 93609
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)
}
}
Upvotes: 1