2015-11-15 42 views
1

我想實現TextWatcher我的應用程序,但是當我輸入一個數字上它具有文本觀察家編輯文本它給我的錯誤是這樣的:的Android TextWatcher

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) 

這是代碼文字觀察者內:

@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)); 
} 
+0

你什麼號碼都可以進入? –

回答

0

首先,加

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

myPercentEditText

問題可能是您輸入的是,而不是.作爲小數點分隔符。

使用

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

防止應用程序崩潰。

+0

是的,我剛剛嘗試過,它給了我這個錯誤消息:System.out:java.lang.NumberFormatException:無效的雙:「」 – Tano

+0

更新我的答案,現在檢查 –

+0

非常感謝你,它的工作!你能告訴我哪裏是我真的好奇的問題:/ – Tano

1

我認爲你的編輯文本值是空的。先檢查它是否爲空,然後進行計算。 使用try catch找到確切的問題。 試試這個吧, link

+0

它實際上並不是空的Swapnil,我試過了達米安提供的解決方案,它的工作,但說實話,我不知道爲什麼:) – Tano

+0

好吧。達米安在評論中給出了確切的理由。希望你明白原因。 –

+0

你現在很友好達米安解釋了我沒有注意到的問題 – Tano