Avoiding a Parsing Error from an EditText in Andro

2020-03-30 03:28发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

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