0

I'm currently using the following line of code to get the value from an edittext:

          double value = Double.valueOf(editText.getText().toString().trim());

This is inside an onclick method. The app I'm developing crashes every time that button is clicked, and I've commented every possible variation of lines in the method and figured out that it's this line of code that causes it to crash. I have no idea why this is happening, but is there an alternative to the same? Parsing it as double didn't work either.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
belle
  • 31
  • 4

4 Answers4

1

Double.parseDouble(String) returns a primitive double type.

Double.valueOf(String) returns a wrapper object of type Double

So you can do it following way,

String strValue = editText.getText().toString().trim();

Check Value is empty or not.

if(!strValue.isEmpty()) {
      double value = Double.parseDouble(strValue);
}

OR

if(!strValue.isEmpty()) {
      Double value = Double.valueOf(strValue);
}
Chirag Savsani
  • 6,020
  • 4
  • 38
  • 74
0

that crash is bc you are usng trim on null or empty value. try adding check

 double value=0.0;
    if(null!=editText && null!=editText.getText() && editText.getText().length() > 0 && !TextUtils.isEmpty(editText.getText().toString())){
     value = Double.parseDouble(editText.getText().toString().trim());
    }else{
    editText.setError("Your message");
    }
Atif AbbAsi
  • 5,633
  • 7
  • 26
  • 47
0

try this:

  String s=editText.getText().toString().trim();

    if(!s.equalsIgnoreCase("")&& !s.equalsIgnoreCase(null)&& !s.isEmpty()) {
        Double value = Double.parseDouble(s);

    }else{
//alert
   }
MurugananthamS
  • 2,395
  • 4
  • 20
  • 49
0

Recommend

Use the isEmpty method of TextUtils class.

double value;
if(!TextUtils.isEmpty(editText.getText().toString().trim())){
    value = Double.parseDouble(editText.getText().toString().trim());
}

Implementation of isEmpty Method of TextUtils :

public static boolean isEmpty(@Nullable CharSequence str) {
    if (str == null || str.length() == 0) {
        return true;
    } else {
        return false;
    }
}
Rajnish suryavanshi
  • 3,168
  • 2
  • 17
  • 23