Android application stopped working

82 views Asked by At

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());

        }
3

There are 3 answers

1
A.S. On

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.
1
codeMagic On

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
  }

}
0
Vitor M. Barbosa On

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.