I have made a tiny Android-project to familiarize myself with user input validation.
The app just has an EditText-control for user input, a button "Compute Result" and a TextView, which shows the result. As input is an integer expected.
The essential part of the code:
buttonCompute.setOnClickListener {
val strInput = inputEditText.text.toString()
if (!TextUtils.isEmpty(strInput)) {
val intInput = strInput.toIntOrNull()
val result = intInput ? .times(10) ? : 0
resultTextView.text = result.toString()
} else {
Toast.makeText(applicationContext, "Please provide a number!",
Toast.LENGTH_LONG).show();
}
}
It works, but it's a lot of code for such a small tasks.
Is there a better way? Does someone know further tricks and helpers, to accomplish the validation easier?
1 Answer 1
There's already a CharSequence.isNotEmpty()
function in the Kotlin standard library, so you could have used that instead of !TextUtils.isEmpty(strInput)
. But you don't even need to check if it's empty when you're using toIntOrNull()
. It will return null if the String is empty. Presumably you would want to show the user the message if they somehow entered something that is not a number (although you can set an EditText to accept only integers), so it becomes simply a null-check. The null-check also allows the value to be smart-cast inside the if-statement.
buttonCompute.setOnClickListener {
val intInput = inputEditText.text.toString().toIntOrNull()
if (intInput != null) {
resultTextView.text = (intInput * 10).toString()
} else {
Toast.makeText(applicationContext, "Please provide a number!",
Toast.LENGTH_LONG).show()
}
}
```