Issue
Recently built my first Android app and have run into a bug that I can't figure out a solution for..
The bug has to do with accepting user input in aa 'editTextNumberDecimal' input. I do some calculations with what is put into the box triggered by 'afterTextChanged' and part of that checks to ensure the box isn't empty. However, if the user starts their input with a period (.) the box is no longer empty and it tries to pass the period into calculations and crashes the app. I'm not sure the best way to address this issue. I've tried checking if the box equals "." and if so ending the function but the app still crashes.
Also, any other tips or improvements that can be made please let me know, android/koltin is new to me.
private fun computeElevation() {
if (inchelevation.text.isEmpty()) {return}
if (inchelevation.text.equals(".")) {return}
val ipc = inchesperclick.selectedItem.toString().toDouble()
val dtt = distancetotarget.selectedItem.toString().toDouble()
val ie = inchelevation.text.toString().toDouble()
val me = (100 / dtt) * ie
val ce = ((100 / dtt) / ipc) * ie
minuteelevation.text = "%.0f".format(me)
clickelevation.text = "%.0f".format(ce)
}
Solution
Use toDoubleOrNull()
instead of toDouble()
.
toDouble throws a NumberFormatException if it fails, so you'd have to wrap it in a try,catch block, otherwise your app will crash because of an unhandled exception.
So instead do this:
private fun computeElevation() {
if (inchelevation.text.isEmpty()) {return}
if (inchelevation.text.equals(".")) {return}
val ipc = inchesperclick.selectedItem.toString().toDoubleOrNull()
val dtt = distancetotarget.selectedItem.toString().toDoubleOrNull()
val ie = inchelevation.text.toString().toDoubleOrNull()
if (ipc == null || dtt == null || ie == null) {
println("There is a missing value")
return
}
val me = (100 / dtt!!) * ie!!
val ce = ((100 / dtt!!) / ipc!!) * ie!!
minuteelevation.text = "%.0f".format(me)
clickelevation.text = "%.0f".format(ce)
}
Answered By - sleepystar96
Answer Checked By - David Marino (JavaFixing Volunteer)