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.
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);
}
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");
}
try this:
String s=editText.getText().toString().trim();
if(!s.equalsIgnoreCase("")&& !s.equalsIgnoreCase(null)&& !s.isEmpty()) {
Double value = Double.parseDouble(s);
}else{
//alert
}
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.