88

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

if (userEmail != null && !userEmail.isEmpty()) {
    Toast.makeText(getActivity(), userEmail, Toast.LENGTH_LONG).show();
    UserEmailLabel.setText(userEmail);
}

But in my Toast I see null is printed. My full code:

private class LoadPersonalData extends AsyncTask<String, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected Void doInBackground(String... res) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("user_id", PrefUserName));
        params.add(new BasicNameValuePair("type", type_data));
        JSONObject json = jsonParser.makeHttpRequest(Url, "POST", params);
        String result = "";
        try {
            result = json.getString("message");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (result.equals("success")) {
            try {
                userEmail = json.getString("email");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);            
        if (userEmail != null && !userEmail.isEmpty()) {
            Toast.makeText(getActivity(), userEmail, Toast.LENGTH_LONG).show();
            UserEmailLabel.setText(userEmail);
        }
    }

How can I check for null and empty string?

Janusz
  • 187,060
  • 113
  • 301
  • 369
user3384985
  • 2,975
  • 6
  • 26
  • 42

11 Answers11

179

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.
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
69

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

if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null")) 
user3384985
  • 2,975
  • 6
  • 26
  • 42
  • 1
    `if (userEmail != null && (!TextUtils.equals(userEmail ,"null")) && (!TextUtils.isEmpty(userEmail))){` also works – user3384985 Nov 23 '14 at 08:38
  • 5
    This may work for emails, but DON’T use `equals("null")` to check for a null username. http://www.bbc.com/future/story/20160325-the-names-that-break-computer-systems – Diti Sep 09 '16 at 09:59
  • 1
    It may perhaps be better to have `userEmail.equalsIgnoreCase("null")` in case of an uppercase null value. – Subby Nov 25 '16 at 10:51
30

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())
Naruto Uzumaki
  • 2,019
  • 18
  • 37
14

Checking for empty string if it is equal to null, length is zero or containing "null" string

public static boolean isEmptyString(String text) {
        return (text == null || text.trim().equals("null") || text.trim()
                .length() <= 0);
    }
hitesh141
  • 963
  • 12
  • 25
4

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;
}
NSK
  • 251
  • 3
  • 10
3

Right way to check empty string.

1. It is faster but not null safe, it will throw NullPointErexception if string is null

if str.isEmpty() then

2. It is also faster but not null safe.

if String.length() = 0 then

3. It is not faster as previous two but it is null safe.

if "".equals(str) then

4. Fouth way

TextUtils.isEmpty(myString)

5. If you want to check for null string.

StringUtils.isEmpty(nullString)

6. If you want to check null and empty string both at same time

if (str == null || str.length() == 0)
Abdul Basit Rishi
  • 2,268
  • 24
  • 30
2

if you check null or empty String so you can try this

 if (yourString != null){
    if(yourString.length==0  && yourString.equals(""))
    Toast.makeText(myClassName.this, "Empty",Toast.LENGTH_LONG).show();
 }else{
    Toast.makeText(myClassName.this, "String null" , Toast.LENGTH_LONG).show();
    }

or using TextUtils class

 if (TextUtils.isEmpty(yourString )) {
       Toast.makeText(myClassName.this, "Empty" , Toast.LENGTH_LONG).show();
    } 
adarsh
  • 403
  • 3
  • 8
2

If using Kotlin:-

 if (TextUtils.isEmpty(userEmail).not()) {
        // do your work
    } else {
        // can show error message userEmail is empty
    }

If using Java:-

  if (!TextUtils.isEmpty(userEmail)) {
        // do your work
    } else {
        // can show error message userEmail is empty
    }
1

My simple solution to test if a string is null:

if (s.equals("null")){ ..... }

There are two cases.

The variable (of type String) is null(doesn't exists): == works.

The variable has a null value, *.equals("null") gives te right boolean value.

See the picture. enter image description here

Paolo
  • 43
  • 2
0

Incase all the answer given does not work, kindly try

String myString = null;

if(myString.trim().equalsIgnoreCase("null")){
    //do something
}
Daniel Nyamasyo
  • 2,152
  • 1
  • 24
  • 23
-1

This worked for me

EditText   etname = (EditText) findViewById(R.id.etname);
 if(etname.length() == 0){
                    etname.setError("Required field");
                }else{
                    Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_LONG).show();
                }

or Use this for strings

String DEP_DATE;
if (DEP_DATE.equals("") || DEP_DATE.length() == 0 || DEP_DATE.isEmpty() || DEP_DATE == null){
}