onTextChanged方法中的NumberFormatException,当输入字符串等于“”

问题描述 投票:-1回答:1

我尝试创建一个仅可以输入数字的警报对话框,如果输入的数字小于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();
java android exception android-alertdialog numberformatexception
1个回答
0
投票

这是因为在onTextChanged()中执行Integer.parseInt,而您刚刚删除或清除了该字段。现在它为空,您正在尝试parseInt一个空字符串。尝试在if条件中添加对空字符串的检查。

if (s.isNotEmpty()) {  // Add this line to check for empty string
   if (Integer.parseInt....){
   } else { 
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.