Avoiding a Parsing Error from an EditText in Andro

2020-03-30 03:45发布

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;
 }

4条回答
啃猪蹄的小仙女
2楼-- · 2020-03-30 03:54

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.

查看更多
Root(大扎)
3楼-- · 2020-03-30 03:59

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.

查看更多
Evening l夕情丶
4楼-- · 2020-03-30 04:04
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.

查看更多
在下西门庆
5楼-- · 2020-03-30 04:16
private double Doublify(EditText editText){
 try{
   return Double.parseDouble(editText.getText().toString());
  }catch(Exception e){
  return 0;
}
 }
查看更多
登录 后发表回答