[android] Check if EditText is empty.

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??

This question is related to android android-edittext

The answer is


with this short code you can delete empty space at start and end of the string. If the string is "" return the message "error" else you ave a string

EditText user = findViewById(R.id.user); 
userString = user.getText().toString().trim(); 
if (userString.matches("")) {
    Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
    return; 
}else{
     Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}

if ( (usernameEditText.getText()+"").equals("") ) { 
    // Really just another way
}

The following works for me all in one statement:

if(searchText.getText().toString().equals("")) 
    Log.d("MY_LOG", "Empty");

First I retrieve a text from the EditText and then convert it to a string and finally comparing it with "" using .equals method.


if(TextUtils.isEmpty(textA.getText())){
            showToast(it's Null");
        }

you can use TextUtils.isEmpty like my Example ! Good luck


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.


"check out this i m sure you will like it."

log_in.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        username=user_name.getText().toString();
        password=pass_word.getText().toString();
        if(username.equals(""))
        {
            user_name.setError("Enter username");
        }
        else if(password.equals(""))
        {
            pass_word.setError("Enter your password");
        }
        else
        {
            Intent intent=new Intent(MainActivity.this,Scan_QRActivity.class);
            startActivity(intent);
        }
    }
});

To editText is empty try another this simple way :

String star = editText.getText().toString();

if (star.equalsIgnoreCase("")) {
  Toast.makeText(getApplicationContext(), "Please Set start no", Toast.LENGTH_LONG).show();
}

Try this out with using If ELSE If conditions. You can validate your editText fields easily.

 if(TextUtils.isEmpty(username)) {
                userNameView.setError("User Name Is Essential");
                return;
         } else  if(TextUtils.isEmpty(phone)) {
                phoneView.setError("Please Enter Your Phone Number");
                return;
            }

Try this

TextUtils.isEmpty(editText.getText());

EditText txtUserID = (EditText) findViewById(R.id.txtUserID);

String UserID = txtUserID.getText().toString();

if (UserID.equals("")) 

{
    Log.d("value","null");
}

You will see the message in LogCat....


I usually do what SBJ proposes, but the other way around. I simply find it easier to understand my code by checking for positive results instead of double negatives. You might be asking for how to check for empty EdiTexts, but what you really want to know is if it has any content and not that it is not empty.

Like so:

private boolean hasContent(EditText et) {
    // Always assume false until proven otherwise
    boolean bHasContent = false; 

    if (et.getText().toString().trim().length() > 0) {
        // Got content
        bHasContent = true;
    }
    return bHasContent;
}

As SBJ I prefer to return "has no content" (or false) as default to avoid exceptions because I borked my content-check. That way you will be absolutely certain that a true has been "approved" by your checks.

I also think the if calling it looks a bit cleaner as well:

if (hasContent(myEditText)) {
// Act upon content
} else {
// Got no content!
}

It is very much dependent on preference, but i find this easier to read. :)


this function work for me

private void checkempForm() {

    EditText[] allFields = { field1_txt, field2_txt, field3_txt, field4_txt};
    List<EditText> ErrorFields =new ArrayList<EditText>();//empty Edit text arraylist
            for(EditText edit : allFields){
                if(TextUtils.isEmpty(edit.getText())){ 

            // EditText was empty
             ErrorFields.add(edit);//add empty Edittext only in this ArayList
            for(int i = 0; i < ErrorFields.size(); i++)
            {
                EditText currentField = ErrorFields.get(i);
                currentField.setError("this field required");
                currentField.requestFocus();
            }
            }
            }

EditText edt=(EditText)findViewById(R.id.Edt);

String data=edt.getText().toString();

if(data=="" || data==null){

 Log.e("edit text is null?","yes");

}

else {

 Log.e("edit text is null?","no");

}

do like this for all five edit text


use TextUtils.isEmpty("Text here"); for single line code


Why not just disable the button if EditText is empty? IMHO This looks more professional:

        final EditText txtFrecuencia = (EditText) findViewById(R.id.txtFrecuencia);  
        final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleStartStop);
        txtFrecuencia.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            toggle.setEnabled(txtFrecuencia.length() > 0);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

        }
       });

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
    }
}

You can use setOnFocusChangeListener , it will check when focus change

        txt_membername.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean arg1) {
            if (arg1) {
                //do something
            } else {
                if (txt_membername.getText().toString().length() == 0) {
                    txt_membername
                            .setError("Member name is not empty, Plz!");
                }
            }
        }
    });

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;
}

I prefer using ButterKnife list binding and then applying actions on the list. For example, with the case of EditTexts, I have the following custom actions defined in a utility class (in this case ButterKnifeActions)

public static <V extends View> boolean checkAll(List<V> views, ButterKnifeActions.Check<V> checker) {
    boolean hasProperty = true;
    for (int i = 0; i < views.size(); i++) {
        hasProperty = checker.checkViewProperty(views.get(i), i) && hasProperty;
    }
    return hasProperty;
}

public static <V extends View> boolean checkAny(List<V> views, ButterKnifeActions.Check<V> checker) {
    boolean hasProperty = false;
    for (int i = 0; i < views.size(); i++) {
        hasProperty = checker.checkViewProperty(views.get(i), i) || hasProperty;
    }
    return hasProperty;
}

public interface Check<V extends View> {
    boolean checkViewProperty(V view, int index);
}

public static final ButterKnifeActions.Check<EditText> EMPTY = new Check<EditText>() {
    @Override
    public boolean checkViewProperty(EditText view, int index) {
        return TextUtils.isEmpty(view.getText());
    }
};

And in the view code, I bind the EditTexts to a list and apply the actions when I need to check the views.

@Bind({R.id.edit1, R.id.edit2, R.id.edit3, R.id.edit4, R.id.edit5}) List<EditView> edits;
...
if (ButterKnifeActions.checkAny(edits, ButterKnifeActions.EMPTY)) {
    Toast.makeText(getContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}

And of course this pattern is extendable to checking any property on any number of views. The only downside, if you can call it that, is the redundancy of views. Meaning, to use those EditTexts, you would have to bind them to single variables as well so that you can reference them by name or you would have to reference them by position in the list (edits.get(0), etc.). Personally, I just bind each of them twice, once to a single variable and once to a the list and use whichever is appropriate.


private boolean isEmpty(EditText etText) {
    if (etText.getText().toString().trim().length() > 0) 
        return false;

    return true;
}

OR As Per audrius

  private boolean isEmpty(EditText etText) {
        return etText.getText().toString().trim().length() == 0;
    }

If function return false means edittext is not empty and return true means edittext is empty...


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;
}

Other answers are correct but do it in a short way like

if(editText.getText().toString().isEmpty()) {
     // editText is empty
} else {
     // editText is not empty
}

Try this out: its in Kotlin

//button from xml
button.setOnClickListener{                                         
    val new=addText.text.toString()//addText is an EditText
    if(new=isNotEmpty())
    {
         //do something
    }
    else{
        new.setError("Enter some msg")
        //or
        Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
    }
}

Thank you


private boolean hasContent(EditText et) {
       return (et.getText().toString().trim().length() > 0);
}

I used TextUtils for this:

if (TextUtils.isEmpty(UsernameInfo.getText())) {
    validationError = true;
    validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}

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


You can also check all the EditText Strings in one If condition: like this

if (mString.matches("") || fString.matches("") || gender==null || docString.matches("") || dString.matches("")) {
                Toast.makeText(WriteActivity.this,"Data Incomplete", Toast.LENGTH_SHORT).show();
            }

try this :

EditText txtUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = usernameEditText.getText().toString();
if (strUserName.trim().equals("")) {
    Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
    return;
}

or use the TextUtils class like this :

if(TextUtils.isEmpty(strUserName)) {
    Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
    return;
}

You can use length() from EditText.

public boolean isEditTextEmpty(EditText mInput){
   return mInput.length() == 0;
}