Android check null or empty string in Android
Use TextUtils.isEmpty( someString )
String myString = null;
if (TextUtils.isEmpty(myString)) {
return; // or break, continue, throw
}
// myString is neither null nor empty if this point is reached
Log.i("TAG", myString);
Notes
- The documentation states that both null and zero length are checked for. No need to reinvent the wheel here.
- A good practice to follow is early return.
From @Jon Skeet comment, really the String
value is "null"
. Following code solved it
if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null"))
Yo can check it with this:
if(userEmail != null && !userEmail .isEmpty())
And remember you must use from exact above code with that order. Because that ensuring you will not get a null pointer exception from userEmail.isEmpty()
if userEmail
is null.
Above description, it's only available since Java SE 1.6. Check userEmail.length() == 0
on previous versions.
UPDATE:
Use from isEmpty(stringVal)
method from TextUtils
class:
if (TextUtils.isEmpty(userEmail))
Kotlin:
Use from isNullOrEmpty
for null or empty values OR isNullOrBlank
for null or empty or consists solely of whitespace characters.
if (userEmail.isNullOrEmpty())
...
if (userEmail.isNullOrBlank())