Android check null or empty string in Android

前端 未结 10 1445
梦如初夏
梦如初夏 2020-12-13 12:07

In my trying AsyncTask I get email address from my server. In onPostExecute() I have to check is email address empty or null

相关标签:
10条回答
  • 2020-12-13 12:38

    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.
    0 讨论(0)
  • 2020-12-13 12:43

    From @Jon Skeet comment, really the String value is "null". Following code solved it

    if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null")) 
    
    0 讨论(0)
  • 2020-12-13 12:43

    You can check it with utility method "isEmpty" from TextUtils,

    isEmpty(CharSequence str) method check both condition, for null and length.

    public static boolean isEmpty(CharSequence str) {
         if (str == null || str.length() == 0)
            return true;
         else
            return false;
    }
    
    0 讨论(0)
  • 2020-12-13 12:45

    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())
    
    0 讨论(0)
提交回复
热议问题