Issue
My app works fine when I first enter a number into the EditText field and does what it is supposed to.
But the number stays in edit text so if I want to change it again I have to clear the previous number. When doing so I get an error java.lang.NumberFormatException: For input string: "".
I understand the reason is because the text has changed so afterTextChanged(p0: Editable?) is called and it is an empty string.
How can I prevent this from crashing the app and allow the user to clear and change the number?
val textChange : EditText = findViewById(R.id.bombCount)
textChange.addTextChangedListener(object : TextWatcher{
var a : Int = 0
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun afterTextChanged(p0: Editable?) {
a = p0.toString().toInt()
GameControl.reset(a,arrCell,marked)
arr = GameControl.startGame(a)
}
})
<EditText
android:id="@+id/bombCount"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:hint="Bomb Count"
android:inputType="number"
/>
Solution
Add a isNotblank
override fun afterTextChanged(p0: Editable?) {
if(p0.toString().isNotBlank()){
a = p0.toString().toInt()
GameControl.reset(a,arrCell,marked)
arr = GameControl.startGame(a)
}
}
or
/* when string is blank you will return a Int*/
a = Int.takeIf{p0.toString().isBlank()}?:p0.toString().toInt()
Answered By - yan sam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.