简体   繁体   English

当输入字符串等于 "" 时 onTextChanged 方法中的 NumberFormatException

[英]NumberFormatException in onTextChanged method when input string equals to ""

I try to make an Alert Dialog where only numbers can be entered and if the entered numbes is less than 5, the OK button is disabled.我尝试制作一个只能输入数字的警报对话框,如果输入的数字小于 5,则“确定”按钮将被禁用。 When I enter something and then delete it, I get NumberFormatException:当我输入一些东西然后删除它时,我得到 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)

Here is a part of the code:这是代码的一部分:

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

This is because inside onTextChanged() you do a Integer.parseInt and you have just deleted or cleared the field.这是因为在 onTextChanged() 中你做了一个 Integer.parseInt 并且你刚刚删除或清除了该字段。 It is now empty and you are trying to parseInt an empty string.它现在是空的,您正在尝试 parseInt 一个空字符串。 Try adding a check for empty string in your if condition.尝试在 if 条件中添加空字符串检查。

if (s.isNotEmpty()) {  // Add this line to check for empty string
   if (Integer.parseInt....){
   } else { 
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM