238

I have 5 EditTexts in android. I would like to know if I could check if all 5 EditTexts are null. Is there any way to do this??

Ashish Neupane
  • 193
  • 2
  • 17
Winona
  • 2,950
  • 2
  • 21
  • 29

30 Answers30

405

I did something like this once;

EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
    Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
    return;
}
cvaldemar
  • 6,983
  • 2
  • 24
  • 18
200
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...

Community
  • 1
  • 1
SBJ
  • 4,089
  • 3
  • 24
  • 27
  • 31
    +1 Checking length is better than checking for empty string IMHO. It would help to trim string before checking length so that whitespace characters wouldn't be counted. Btw, any particular reason of not using `return etText.getText().toString().trim().length() == 0` instead of true/false branches? – Audrius Jun 09 '11 at 09:58
  • 1
    well I guess code readability and maintainability... – WiZarD Jun 25 '13 at 18:28
  • if EditText.setInputType(InputType.TYPE_CLASS_NUMBER); number then use this. – Zala Janaksinh Jul 20 '13 at 06:32
  • Yes its working because its depend on length... – SBJ Jul 22 '13 at 10:29
  • `private Boolean isEmpty(EditText etText){return etText.Text.ToString().Trim().Length == 0;}` VS 2019 – Siddharth Rout May 09 '20 at 17:32
169

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

MilapTank
  • 9,988
  • 7
  • 38
  • 53
39

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;
}
Kamil Gosciminski
  • 16,547
  • 8
  • 49
  • 72
Houcine
  • 24,001
  • 13
  • 56
  • 83
  • 3
    ...this is the best way to do this. Other examples allow input that is not being accounted for. – dell116 Mar 16 '12 at 17:25
31

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
    }
}
Qw4z1
  • 3,041
  • 1
  • 24
  • 36
  • isEmpty() doesnt check for blank space , try entering one space – Hunt Mar 17 '13 at 12:43
  • 3
    @Hunt That's true, but then it would not be empty or null anymore. Maybe TextUtils.isEmpty(sUserName.trim()) would be appropriate, to remove all blanks, just in case the user has entered one or several blank spaces? – Qw4z1 Mar 17 '13 at 14:18
  • `isEmpty()` takes a `CharSequence`, which `Editable` extends, so there's no need to call `.toString()` on it. – karl Aug 20 '14 at 23:04
  • @karl Good point! Updated my answer. – Qw4z1 Aug 22 '14 at 07:53
22

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
}
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
14

Try this

TextUtils.isEmpty(editText.getText());
Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
martyglaubitz
  • 992
  • 10
  • 21
8

You can use length() from EditText.

public boolean isEditTextEmpty(EditText mInput){
   return mInput.length() == 0;
}
Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
JPMagalhaes
  • 3,611
  • 1
  • 25
  • 26
7

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. :)

Community
  • 1
  • 1
sigcontSE
  • 73
  • 1
  • 3
7

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) {

        }
       });
Igor Zelaya
  • 4,167
  • 4
  • 35
  • 52
  • Disabling user interfaces is not recommended by Joel Spolsky in [his article](https://www.joelonsoftware.com/2008/07/01/dont-hide-or-disable-menu-items/). – Second Person Shooter Jul 24 '21 at 21:02
4

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;
}
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
4
if(TextUtils.isEmpty(textA.getText())){
            showToast(it's Null");
        }

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

Erik Chau
  • 57
  • 5
4

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();
}
3
private boolean hasContent(EditText et) {
       return (et.getText().toString().trim().length() > 0);
}
Edwin Alex
  • 5,118
  • 4
  • 28
  • 50
LMK
  • 2,882
  • 5
  • 28
  • 52
3

I used TextUtils for this:

if (TextUtils.isEmpty(UsernameInfo.getText())) {
    validationError = true;
    validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}
nstCactus
  • 5,141
  • 2
  • 30
  • 41
wildapps
  • 45
  • 4
2

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();
            }
2

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.

Abhishek Balani
  • 3,827
  • 2
  • 24
  • 34
2

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;
            }
Sami Khan
  • 31
  • 3
2

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;
}
dreinoso
  • 1,479
  • 17
  • 26
1
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....

Ankur
  • 5,086
  • 19
  • 37
  • 62
Jothi
  • 11
  • 2
1

"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);
        }
    }
});
Gwenc37
  • 2,064
  • 7
  • 18
  • 22
Aris_choice
  • 392
  • 2
  • 18
1

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

Anand Savjani
  • 2,484
  • 3
  • 26
  • 39
1

This function work for me

private void checkForm() {
    EditText[] allFields = {
        field1_txt,
        field2_txt,
        field3_txt,
        field4_txt
    };
    
    List < EditText > ErrorFields = new ArrayList < EditText > (); 

    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();
            }
        }
    }
}
Boken
  • 4,825
  • 10
  • 32
  • 42
taha mosaad
  • 567
  • 5
  • 13
1

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.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
0
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

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Aamirkhan
  • 5,746
  • 10
  • 47
  • 74
0

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();
}
lostAtSeaJoshua
  • 1,695
  • 2
  • 21
  • 34
Guru
  • 186
  • 14
0

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!");
                }
            }
        }
    });
hoang lam
  • 56
  • 3
0
if ( (usernameEditText.getText()+"").equals("") ) { 
    // Really just another way
}
Sydwell
  • 4,954
  • 1
  • 33
  • 36
0

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.

Saad Farooq
  • 13,172
  • 10
  • 68
  • 94
0

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

RPichioli
  • 3,245
  • 2
  • 25
  • 29