Reputation: 37
I am making android calculator app for class assignment. When i press plusminus (+/-) key first and then input any numeric key; my application stops working. But when i input numeric key and then press plusminus button it works fine.
else if (v.getId() == R.id.plusminus){
Double newNumber = Double.parseDouble(textdisplay.getText().toString());
total = newNumber * (-1);
textdisplay.setText(total.toString());
}
Upvotes: 1
Views: 78
Reputation: 3646
This line
Double newNumber = Double.parseDouble(textdisplay.getText().toString());
is probably throwing an exception (either NullPointer
or NumberFormat
), so check for textdisplay
's value before trying to parse.
Upvotes: 0
Reputation: 44571
When your app crashes, you get errors in the logcat. It is most helpful if you post those along with your question and relevant code. However, here I am pretty sure it is a parsing/error-checking problem
When i press plusminus (+/-) key first and then input any numeric key; my application stops working
When you press this key, you aren't checking for valid input so it is trying to parse empty text. You need to do some error-checking such as try/catch
to check for invalid input. Something like
else if (v.getId() == R.id.plusminus){
try {
Double newNumber = Double.parseDouble(textdisplay.getText().toString());
total = newNumber * (-1);
textdisplay.setText(total.toString());
}
catch (NumberFormatException e) {
// maybe show some relevant message here with a Toast or something
// to let the user know invalid input was entered
}
}
Upvotes: 1
Reputation: 4574
Please check your String from textdisplay to be empty. Because Double.parseDouble will throw a Exception when the String is empty or not numeric.
else if (v.getId() == R.id.plusminus){
String number = textdisplay.getText().toString();
if(number == null) return; //exits function
if(number.equals("")) return; //exits function
//you could do more checks here
Double newNumber = Double.parseDouble(number);
total = newNumber * (-1);
textdisplay.setText(total.toString());
}
Please also have a look at the Double Documentation here LINK
Double.parseDouble(String s)
Throws:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable double.
Upvotes: 0