1

When the field is left blank it makes the app crash. How can i stop it ?

EditText editText = (EditText)findViewById(R.id.editText);
userNumber = Integer.parseInt(editText.getText().toString());

I tried giving it a .setError("Don't leave this blank!"), but it doesn't seem to do the thing, the app crashes there.

Screenshots:
screen-shot error-message

Dhaval Patel
  • 10,119
  • 5
  • 43
  • 46
Dawid
  • 585
  • 5
  • 26

3 Answers3

2

trying to parseInt from an empty or null string raises a FormatException. So, either wrap your code inside a try/catch:

try {
  userNumber = Integer.parseInt(editText.getText().toString());
}catch(Exception e){
    // friendly error to the user: field is incorrect
}

or use an if statement to make sure the editText is not empty:

if(editText.getText().length() > 0){
     // your code
}

The if solution supposes that your editText only accepts numbers (using the attribute android:inputType="number" in your xml layout).

As a side note, for good practice, note that it is always wise to wrap a parseInt inside a try/catch.

Derlin
  • 9,572
  • 2
  • 32
  • 53
1

This code can give you an idea,

String input = editText.getText().toString();
if(input.length() > 0){
    try {
        int userNumber = Integer.parseInt(input);

        // Write your code here

    } catch (Exception e) {
        Toast.makeText(this, "Enter only a number!", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
} else{
    Toast.makeText(this, "Enter a number!", Toast.LENGTH_SHORT).show();
}
K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33
1
   Use this it will help you and remove your crash    


EditText editText = (EditText)findViewById(R.id.editText);

if(userNumber.length() > 0)
{
set your error screen is empty
}
else
{
userNumber = Integer.parseInt(editText.getText().toString());
}
Neeraj Sharma
  • 191
  • 18