Java 当输入字符串等于“时,ContextChanged方法中的NumberFormatException&引用;

Java 当输入字符串等于“时,ContextChanged方法中的NumberFormatException&引用;,java,android,exception,android-alertdialog,numberformatexception,Java,Android,Exception,Android Alertdialog,Numberformatexception,我尝试创建一个警报对话框,其中只能输入数字,如果输入的数字小于5,则“确定”按钮将被禁用。当我输入某个内容并将其删除时,我会得到NumberFormatException: Process: com.example.emotionsanalyzer, PID: 9143 java.lang.NumberFormatException: For input string: "" at java.lang.Integer.parseInt(Integer.java:627)

我尝试创建一个警报对话框,其中只能输入数字,如果输入的数字小于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,并且刚刚删除或清除了该字段。它现在是空的,您正试图解析一个空字符串。 尝试在if条件中添加空字符串检查

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

谢谢。确切地说,我把它改为if(!s.toString().isEmpty())