1
\$\begingroup\$

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?

asked Oct 4, 2021 at 5:01
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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()
 }
}
```
answered Oct 4, 2021 at 13:45
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.