To stackoverflow community, I created this method to turn some EditText fields in doubles. I added the if statement specifically for the purpose of avoiding parse error because I know that several of my EditText fields will be left blank. However, they still keep coming at runtime. Does anybody know the correct way to avoid parsing fields that are blank? Thank you very much.
private double Doublify(EditText editText){
if(!(editText.getText().equals(null))){
return Double.parseDouble(editText.getText().toString());
}
return 0;
}
Why don't you try something like this?
EDIT: Note, this is untested...no compiler here. :'(
Since it throws a NumberFormatException if the string is null, just catch the exception to return 0 if it's null or not formatted correctly.
First of all, your text won't be null. It will be an empty string - those are two different things. You also don't use
equals
to test for null, you just use==
.However, the proper way to check for bad strings (could also be somebody entering text!) is to just handle the exception:
You can also catch
NullPointerException
if you suspect editText's text could be null.or surround it with a try catch block and return 0 when there is an exception.