![](/img/trans.png)
[英]This code throws an exception for the line Integer.parseInt(data[2])
[英]Android: Integer.parseInt() never throws exception
我的活動中有一些EditText。 用戶必須填寫它們並確認他的輸入。 一些EditText僅用於數字。 為了確保只有有效值,我嘗試使用Integer.parseInt(。。。)將輸入轉換為Integer。 問題是無論NumberFormatException是什么字符串都不會引發。 我調試了問題,並且每次都會執行對應的行,但不會引發異常。
這是我的方法的代碼:
private boolean formNotEmpty()
{
boolean returnValue = true;
for(int i = 0; i < _editText.size();i++){
if(_editText.get(i).getText().toString().trim().length() == 0)
{
returnValue = false;
_toastMessage = "Es müssen alle Felder ausgefüllt werden.";
break;
}else if(_editText.get(i).getHint().equals(getResources().getString(R.string.rentactivity_hint_userPLZ))
||_editText.get(i).getHint().equals(getResources().getString(R.string.rentactivity_hint_userTelefon)))
{
try{
Integer.parseInt(_editText.get(i).getText().toString().trim());
}catch(NumberFormatException e)
{
_toastMessage += "In "+_editText.get(i).getHint().toString() +" dürfen nur Zahlen stehen. \n";
}
}
}
return returnValue;
}
我忘記將catch塊中的returnValue設置為false。 如果該方法返回true,則_toastMessage將獲得一個新字符串。 這就是我認為永遠不會拋出異常的原因。 對於造成的麻煩,我感到非常抱歉。
非常感謝你
如果要依靠代碼拋出異常,並且希望以此作為驗證數據以僅接受數字的手段,那么這不是正確的方法。 異常處理不應像您建議的那樣顯式地用作if-else。 一種簡單,也許更正確的方法來完成您想要的操作:
在布局xml中聲明
android:inputType="number"
對於該特定的edittext,您只想將條目限制為數字。
這樣做時,當您嘗試以用戶身份填充該editText時,只能獲得鍵入數字的選項。 在xml中添加此代碼后,您無需依賴Integer.parseInt()API來引發異常即可進行驗證。
您也可以使用EditText的attr:
android:digits="0123456789."
http://developer.android.com/reference/android/widget/TextView.html#attr_android:digits
之后,用戶只能寫數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.