添加验证,以便EditText字段不能为空

时间:2016-05-05 17:34:20

标签: android

所以我试图在我的btnSubmit上添加验证,这将检查所有editText字段在存储到数组之前是否有某种数据。有人能帮忙吗?

       if (btnSubmit == null) throw new AssertionError();
    btnSubmit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            if(editMod.getText().length()==0){
                editMod.setError("Please fill in all fields");
            }
            else if(editRoom.getText().length()==0){
                editRoom.setError("Please fill in all fields");
            }

            if (editMod.getText() != null) {
                strModule = editMod.getText().toString();
            }
            if (editRoom.getText() != null) {
                strRoomInfo = editMod.getText().toString();
            }

            inputData = strDay + " " + strTime + " " + strDuration + " " + strType + " " + strModule + " " + strRoomInfo;
            parent.addItem(inputData);
            try {
                writeFile();
            } catch (Exception e) {
                Log.e("Writing to file Failed.", " ");
            }
        }
    });
}

2 个答案:

答案 0 :(得分:1)

这里有什么编辑模式? EditText或TextInputLayout?

对于此当前代码,这是更新版本:

    if (btnSubmit == null) throw new AssertionError();
btnSubmit.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        if(editMod.getText().toString().isEmpty()){
            editMod.setError("Please fill in all fields");
        }
        else if(editRoom.getText().toString().isEmpty()){
            editRoom.setError("Please fill in all fields");
        }

        if (editMod.getText().toString() != null) {
            strModule = editMod.getText().toString();
        }
        if (editRoom.getText().toString() != null) {
            strRoomInfo = editMod.getText().toString();
        }

        inputData = strDay + " " + strTime + " " + strDuration + " " + strType + " " + strModule + " " + strRoomInfo;
        parent.addItem(inputData);
        try {
            writeFile();
        } catch (Exception e) {
            Log.e("Writing to file Failed.", " ");
        }
    }
});
}

更新您的问题并添加xml代码和其他Java代码。

答案 1 :(得分:0)

试试这段代码:

if (TextUtils.isEmtpy(<Your EditText here>.getText().toString())) {
   //Empty
}