Android Kotlin中EditText空值时避免计算崩溃的实现方案
Hey there! Let's sort out that crash and get your calculation logic working smoothly. The issue here is that when you call toDouble() directly on an empty or invalid string, it throws a NumberFormatException which crashes your app. Instead, we'll use Kotlin's safe conversion function to handle empty inputs gracefully.
The Problem with Your Current Code
Your current code assumes all EditText fields have valid numeric values, but if any field is empty (or has non-numeric text), toDouble() will crash the app:
calculate.setOnClickListener { val s = distance.text.toString().toDouble() val u = initalVelocity.text.toString().toDouble() val t = time.text.toString().toDouble() val a = (((2* s))-(2*(u*t)))/(t*t) answer.setText("answer $a m/(s)^2") }
The Solution: Safe Conversion with toDoubleOrNull()
Kotlin provides toDoubleOrNull() which returns null if the string can't be converted to a valid Double (like empty strings or non-numeric text). We'll use this to check if all inputs are valid before calculating, and show an error message if any are missing.
Here's the updated MainActivity.kt code:
calculate.setOnClickListener { // Safely convert input strings to nullable Double types val s = distance.text.toString().toDoubleOrNull() val u = initalVelocity.text.toString().toDoubleOrNull() val t = time.text.toString().toDoubleOrNull() // Check if all inputs are non-null and valid if (s != null && u != null && t != null) { // Perform calculation only when all values are present val a = ((2 * s) - (2 * u * t)) / (t * t) answer.text = "answer $a m/(s)^2" } else { // Show prompt if any input is missing or invalid answer.text = "Put a value" } }
Key Changes Explained
toDoubleOrNull(): ReplacestoDouble()to avoid crashes from empty/invalid inputs. It returnsnullinstead of throwing an exception, which aligns with what you tried to do with "DecimalorNull" (you were probably referring to this Kotlin built-in function).- Null Check: We verify that
s,u, andtare all non-null before running the calculation. If any value isnull, we set the error message in theanswerTextView. - Simplified Formula: Removed unnecessary parentheses from the calculation to make the code cleaner, without changing the underlying math logic.
Your Layout XML (for reference)
<EditText android:id="@+id/distance" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="@string/distance" android:inputType="number|numberDecimal|numberSigned" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.094" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.034" /> <EditText android:id="@+id/initalVelocity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="@string/initialVelocity" android:inputType="number|numberDecimal|numberSigned" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.094" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.133" /> <EditText android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="@string/time" android:inputType="number|numberDecimal|numberSigned" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.094" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.232" /> <TextView android:id="@+id/answer" android:layout_width="219dp" android:layout_height="37dp" android:text="@string/answer" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.096" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.35" /> <Button android:id="@+id/calculate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/calculate" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.462" />
This should prevent the crash and show your desired prompt whenever any input is missing or invalid. Give it a try!
内容的提问来源于stack exchange,提问作者a2krocks




