简体   繁体   中英

What does getText() return for an empty EditText?

I am trying to check if the EditText is empty. For this, I tried this:

  String text = gateNumberEditText.getText().toString();
  if (text.equals("")){
      \\do something
  } else {
       \\do something else
  }

Also tried: text == null , text == "" , text.equals(null)

Nothing seems to work, it always passes to the else. Why is that?

**isEmpty() solved my problem. But I'll be happy if someone explain me why it didn't work at first?

Please try this:

String text = gateNumberEditText.getText().toString().trim();
if (text==null || text.equals("")) {
   // do something
}
else {
   // do something else
}

A summary of my previous comments:

String text = gateNumberEditText.getText().toString();
  if (text.equals("")){

                \\do something
            }else {
                \\do something else
            }

If you had a null , this code would have thrown a NullPointerException on the toString() method call.

Seeing as getText() returns a String , there is no reason to call toString()

When you want to compare values of String objects, always use the equals(IgnoreCase)() method.

Also, remember, " " (a space) and "" are not two identical values, so comparing them will indeed return false . Change your code to this:

String text = gateNumberEditText.getText().trim();
// the trim() method will remove all leading and trailing spaces
  if (text.isEmpty()){ // this method of the String class, will check the length of the String.
// after the trim(), for an empty String (or only spaces), that would be zero
                \\do something
            }else {
                \\do something else
            }

You should use TextUtils class's isEmpty method, which returns a boolen value, to check if the edit text is empty or not.

if(!TextUtils.isEmpty(editText.getText().toString())) {
// Do something
} else{
 //Do something else
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM