Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if my EditText fields are empty? [closed]

People also ask

What does an empty EditText return?

It will return true if its empty/null.

How do I know if EditText is empty Kotlin?

This example demonstrates how to Check if Android EditText is empty in Kotlin. Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.

How can I tell if EditText is clicked?

You can use View. OnFocusChangeListener to detect if any view (edittext) gained or lost focus. This goes in your activity or fragment or wherever you have the EditTexts.


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

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


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


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

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

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

TextUtils.isEmpty(editText.getText());