I'm new to programming and I'm learning on the go.
I've got my app to do everything i need it to but when my text fields are empty and the calculate button is hit the app shuts down and i get java.lang.NumberFormatException: empty String. At this point i can't figure out how to avoid this.
/** Pull data from edittext **/
double ang = Double.parseDouble(AngleeditText.getText().toString());
double tnr = Double.parseDouble(TnreditText.getText().toString());
Any help is greatly appreciated. Thankk you in advance.
/** post to textView **/
XofftextView.setText(String.format("X Offset : %.4f", resultx));
ZofftextView.setText(String.format("Z Offset : %.4f", resultz));
Make sure you have checked null or empty before parsing to desired format.
Solution
String text = AngleeditText.getText().toString();
if (text != null && text.length() > 0) {
double ang = Double.parseDouble(text);
// Use ang value
}
Before processing input you should sanity check it.
Eg there's nothing wrong with doing something like:
String x = AngleeditText.getText().toString();
String y = TnreditText.getText().toString();
if (x == null || x.equalsIgnoreCase("") || y == null || y.equalsIgnoreCase("")) {
return;
}
Just as a general rule the parsing should also always be wrapped in a try/catch control structure. Eg
double ang = 0.0;
double trn = 0.0;
try {
ang = Double.parseDouble(x);
trn = Double.parseDouble(y);
} catch (Exception e) {
//Optionally system.out or system.err some message here
System.out.println("Couldn't parse" + x + " or " + y);
return;
}
NB: you have to declare (and initialise) ang and trn if you want to use them outside of the try/catch block.
Additionally, even before trying to parse the input you might want to run it through an appropriate regex to make sure it's actually a legit number.
Biggkev. Welcome to programming world :)
Should I assume that resultx and resultz came from ang and tnr ? If so:
I believe when .ToString() function is called, AngleeditText.getText() returns no value. Since there is no reference, an exception blows afterwards, when you set resultx and resultz.
I suggest that you validate first if resultx and resultxz or AngleeditText.getText() and TnreditText.getText() return values different from null and empty.
You could create a method for that and include a validation like:
if(resultx != null && !resultx.isEmpty())
XofftextView.setText(String.format("X Offset : %.4f", resultx));
I hope this is helpful.
Cheers
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.