尝试验证空字段时,应用程序崩溃并出现错误 'Could not execute method for android:onClick'

App crashes with error 'Could not execute method for android:onClick' when try to validate empty field

我尝试创建空字段验证,如果用户不输入任何内容 String/Integer 而只是按下按钮,他将收到提示该字段为空的弹出窗口。

我会感谢任何帮助。

查看下面我的代码:

...

    public void clickCheck (View view) {
        EditText editText = (EditText) findViewById(R.id.userType);
        Integer userNum = Integer.parseInt(editText.getText().toString());
        String userField = editText.getText().toString().trim();
        String message = "";


        if (userField.isEmpty()) {
            message = "please input something!!!!!";
        } else {
            Shape mynumber = new Shape();
            mynumber.number = userNum;
            if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == false)) {

                makeToast("The number " + userNum + " is a Square number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is a Triangular number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == false)) {
                makeToast("The number " + userNum + " is a not Square or Triangular shape");
            } else if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is both Square & Triangular shapes");
            }

        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

该问题与

有关
Integer userNum = Integer.parseInt(editText.getText().toString());

它可能会抛出 NumberFormatException,您将无法到达验证。

你可以这样试试

    public void clickCheck (View view) {
        EditText editText = (EditText) findViewById(R.id.userType);
        String userField = editText.getText().toString().trim();
        String message = "";
        if (userField.isEmpty()) {
            message = "please input something!!!!!";
        } else {
            Shape mynumber = new Shape();
            Integer userNum;
            try {
                userNum = Integer.parseInt(editText.getText().toString());
            }catch (NumberFormatException ex) {
                message = "Not an integer";
            }
            mynumber.number = userNum;
            ...
        }
    }

谢谢@Hakob,你的建议很有效。 我后来的问题是因为我的 Toast 命令没有被正确定义。

所以我有这个:message = "please input something!!!!!";

然后我改为:makeToast("please input something!!!!!");

实际上我根本没有定义 Toast 命令,所以应用程序不理解它应该弹出一条消息:)。

再次感谢大家的帮助。