NumberFormatException in onTextChanged method when input string equals to ""

Mateusz Ceranka :

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. When I enter something and then delete it, I get 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();
JoM :

This is because inside onTextChanged() you do a Integer.parseInt and you have just deleted or cleared the field. It is now empty and you are trying to parseInt an empty string. Try adding a check for empty string in your if condition.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27177&siteId=1