1

I am trying to implement TextWatcher to my application, but when I enter a number into the edit text which has text watcher on it it gives me error like this:

AndroidRuntime:at java.lang.StringToReal.invalidReal(StringToReal.java:63)
AndroidRuntime:at java.lang.StringToReal.parseDouble(StringToReal.java:267)
AndroidRuntime:at java.lang.Double.parseDouble(Double.java:301)

And this is the code inside the text watcher:

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

    myPercent = Double.parseDouble(s.toString());
    myPrice =  Double.parseDouble(priceShow.getText().toString());
    finalPrice = myPrice*(myPercent/100);
    priceAfterDiscount.setText(String.valueOf(finalPrice));
}
Tano
  • 609
  • 8
  • 23

2 Answers2

1

I think your edit text value is empty. check first if its empty or not, then do the calculation. use try catch to find exact problem. try this, link

Community
  • 1
  • 1
0

First of all, add

android:inputType="number"
android:singleLine="true"

to your myPercent EditText.

Problem is probably that you are entering , instead of . as decimal separator.

Use

try { 
    if (!s.toString().equals("") && !priceShow.getText().toString().equals("")) {
        myPercent = Double.parseDouble(s.toString());
        myPrice =  Double.parseDouble(priceShow.getText().toString());
        finalPrice = myPrice*(myPercent/100);
        priceAfterDiscount.setText(String.valueOf(finalPrice));
    }
} catch (NumberFormatException e) {
    e.printStackTrace();
} 

to prevent application from crashing.

Damian Kozlak
  • 7,065
  • 10
  • 45
  • 51
  • yes I have just tried it, it gives me this error message: System.out: java.lang.NumberFormatException: Invalid double: "" – Tano Nov 15 '15 at 14:49
  • thank you so much, it worked !!! Can you tell me where was the problem I am really curious :/ – Tano Nov 15 '15 at 14:58
  • `TextWatcher` detected change within `s`, so `onTextChanged` has been called, but `s` was probably still empty in this moment, so by making `Double.parseDouble(s.toString());` you trying to make `double` from empty `String` `""`. All I did is just adding `if` which prevents execution of this method if `String` is empty. – Damian Kozlak Nov 15 '15 at 15:03