Saksham Khurana
Saksham Khurana

Reputation: 1010

Check if EditText with "inputType = number" is null

I am trying to check if the input in EditText in null or not .

if(editTextSum.getText().toString() != null) {
  userStartingBalance = Integer.valueOf(editTextSum.getText().toString());
} else {
  userStartingBalance = 0;
}

Here userStartingBalance is Integer type .

But I am getting an error everytime that

Can't convert " " into int , and the line is pointed to the 'if case' if I don't enter anything.

Why is it not going to else case?

What should be the workaround?

Upvotes: 0

Views: 153

Answers (3)

Mamtaz Hussain
Mamtaz Hussain

Reputation: 1

Why is it not going to else case ?

Because you are calling ToString() on Null. If the field has no value present then it wil set NULL to it and if you try to run the toString() method you will receive this error. Do the Null check before retrieving the value.

Workaround

if( editTextSum.getText() != null )
{
    userStartingBalance = Integer.parseInt(editTextSum.getText().toString());
}
else
{
    userStartingBalance =0;
}

Upvotes: 0

Bryan Herbst
Bryan Herbst

Reputation: 67209

You are not properly handling the case in which your EditText simply has no content in it.

In this case, editTextSum.getText().toString() will not return null (in fact, that should never be null). Instead, it will return an empty string.

Instead, you might want to try editTextSum.getText().toString().isEmpty() instead,. isEmpty() will return true if the length is 0.

Upvotes: 2

Rene Limon
Rene Limon

Reputation: 624

try:

Integer.parseInt(editTextSum.getText().toString())

Upvotes: 1

Related Questions