Spike
Spike

Reputation: 147

how to avoid the exception when nothing is entered in edittext?

I have created edittexts in which user can enter numbers. In my app user can submit the values by clicking on submit button.(Note: Initially I set all 3 EditTexts to "" with setText() in the code)After submitting I have kept these following lines to retrieve values in the method.

String st1=editText1.getText().toString();
int tempVal1=Integer.parseInt(st);
String st2=editText2.getText().toString();
int tempVa2=Integer.parseInt(st);
String st3=editText2.getText().toString();
int tempVal3=Integer.parseInt(st);

But here my problem is if the user doesn't enter any value in the first editText and fills only 2nd and 3rd and submits, then the value in the tempVal1 should be 0. But I am getting exception becuase of the first statement because of not having any data. How to avoid this exception and keep the tempVal 0 when he doesn't fill anything in the respective edittext?

I have one more doubt, when I add this int x=Integer.valueOf(editText.getText()); line, I am getting the following error. Why?The method valueOf(String) in the type Integer is not applicable for the arguments (Editable)

Please clarify my doubts.

Upvotes: 2

Views: 4239

Answers (4)

jeet
jeet

Reputation: 29199

You must be getting NumberFormatException, as String is blank, and blank cant be parsed into integer. So, initialize these variables with 0. and put parsing code into try catch. as below:

int tempVal1=0;
int tempVal2=0;
int tempVal3=0;

String st1=editText1.getText().toString();
try{    
  tempVal1=Integer.parseInt(st1);
}
catch(NumberFormatException ex) {}

String st2=editText2.getText().toString();
try{
   tempVal2=Integer.parseInt(st2);
}
catch(NumberFormatException ex){}

String st3=editText2.getText().toString();
try{    
   tempVal3=Integer.parseInt(st3);
}
catch(NumberFormatException ex){}

Upvotes: 0

Lucifer
Lucifer

Reputation: 29670

You need to check the EditText before converting it into Number.

if( !editText1.getText().toString().equals("") && editText1.getText().toString().length() > 0 )
{
    // Get String
    Integer.parseInt(editText1.getText().toString());
}

Upvotes: 7

Vinay W
Vinay W

Reputation: 10190

The method valueOf(String) in the type Integer is not applicable for the arguments (Editable)

means it is looking for a String argument but gets an Editable

try x=Integer.valueOf(editText.getText().toString());

And about the Exception :

Surround your code with Try & Catch , or do Null checks before you parse integers.

Upvotes: 0

Chirag
Chirag

Reputation: 56935

You have to check the condition for edit text is not null or there is no value in edit text like below.

Condition for EditText is not Blank.

if(editText1.getText().toString().length() != 0)
{
    // Get String
    Integer.parseInt(editText1.getText().toString());
}

Upvotes: 1

Related Questions