开发者

Avoiding a Parsing Error from an EditText in Android

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 Doublif开发者_StackOverflow社区y(EditText editText){
  if(!(editText.getText().equals(null))){
   return Double.parseDouble(editText.getText().toString());
  }
  return 0;
 }


Why don't you try something like this?

private double Doublify(EditText editText) {
    try {
        Double double = Double.parseDouble(editText.getText().toString());
    } catch (NumberFormatException e) {
        return 0;
    }
    return double;
}

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:

private double Doublify(EditText editText){
     try {
       return Double.parseDouble(editText.getText().toString());
     } catch (NumberFormatException e) {
        return 0;
     }
 }

You can also catch NullPointerException if you suspect editText's text could be null.


private double Doublify(EditText editText) { 

if(editText.getText() != null && !"".equalsIgnoreCase(editText.getText().toString)) {
 return Double.parseDouble(editText.getText().toString()); 
}
 return 0; 
}

or surround it with a try catch block and return 0 when there is an exception.


private double Doublify(EditText editText){
 try{
   return Double.parseDouble(editText.getText().toString());
  }catch(Exception e){
  return 0;
}
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜