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));
}
4

2 回答 2

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

于 2015-11-15T15:00:23.283 回答
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.

于 2015-11-15T14:46:10.653 回答