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