Check if EditText is empty. [closed]

2018-12-31 17:26发布

I have 5 EditTexts in android for users to input. I would like to know if I could have a method for checking all the 5 EditTexts if they are null. Is there any way to do this??

30条回答
看淡一切
2楼-- · 2018-12-31 17:54

I use this method, that uses trim() to avoid blank spaces :

EditText myEditText = (EditText) findViewById(R.id.editUsername);
if ("".equals(myEditText.getText().toString().trim()) {
    Toast.makeText(this, "You did not enter a value!", Toast.LENGTH_LONG).show();
    return;
}

an example if you have several EditText´s

if (("".equals(edtUser.getText().toString().trim()) || "".equals(edtPassword.getText().toString().trim()))){
        Toast.makeText(this, "a value is missing!", Toast.LENGTH_LONG).show();
        return;
}
查看更多
余生无你
3楼-- · 2018-12-31 17:54

I wanted to do something similar. But getting the text value from edit text and comparing it like (str=="") wasn't working for me. So better option was:

EditText eText = (EditText) findViewById(R.id.etext);

if (etext.getText().length() == 0)
{//do what you want }

Worked like a charm.

查看更多
爱死公子算了
4楼-- · 2018-12-31 17:55

Way late to the party here, but I just have to add Android's own TextUtils.isEmpty(CharSequence str)

Returns true if the string is null or 0-length

So if you put your five EditTexts in a list, the full code would be:

for(EditText edit : editTextList){
    if(TextUtils.isEmpty(edit.getText()){
        // EditText was empty
        // Do something fancy
    }
}
查看更多
人间绝色
5楼-- · 2018-12-31 17:56

For validating EditText use EditText#setError method for show error and for checking empty or null value use inbuilt android class TextUtils.isEmpty(strVar) which return true if strVar is null or zero length

EditText etUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = etUserName.getText().toString();

 if(TextUtils.isEmpty(strUserName)) {
    etUserName.setError("Your message");
    return;
 }

Image taken from Google search

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 17:56
if ( (usernameEditText.getText()+"").equals("") ) { 
    // Really just another way
}
查看更多
十年一品温如言
7楼-- · 2018-12-31 17:57

You could call this function for each of the edit texts:

public boolean isEmpty(EditText editText) {
    boolean isEmptyResult = false;
    if (editText.getText().length() == 0) {
        isEmptyResult = true;
    }
    return isEmptyResult;
}
查看更多
登录 后发表回答