[英]NumberFormatException in onTextChanged method when input string equals to ""
我嘗試制作一個只能輸入數字的警報對話框,如果輸入的數字小於 5,則“確定”按鈕將被禁用。 當我輸入一些東西然后刪除它時,我得到 NumberFormatException:
Process: com.example.emotionsanalyzer, PID: 9143
java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.emotionsanalyzer.ui.CameraActivity$3.onTextChanged(CameraActivity.java:245)
這是代碼的一部分:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
builder.setView(input);
builder.setPositiveButton("OK", (dialog, which) -> {
intervalInMs = Integer.parseInt(input.getText().toString());
});
builder.setNegativeButton("Anuluj", (dialog, which) -> dialog.cancel());
AlertDialog dialog = builder.create();
input.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (Integer.parseInt(s.toString()) >= 5){
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
else{
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
dialog.show();
這是因為在 onTextChanged() 中你做了一個 Integer.parseInt 並且你剛剛刪除或清除了該字段。 它現在是空的,您正在嘗試 parseInt 一個空字符串。 嘗試在 if 條件中添加空字符串檢查。
if (s.isNotEmpty()) { // Add this line to check for empty string
if (Integer.parseInt....){
} else {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.