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