[android] Android check null or empty string in Android

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?

This question is related to android android-asynctask android-fragmentactivity

The answer is


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){
}

All you can do is to call equals() method on empty String literal and pass the object you are testing as shown below :

 String nullString = null;
 String empty = new String();
 boolean test = "".equals(empty); // true 
 System.out.println(test); 
 boolean check = "".equals(nullString); // false 
 System.out.println(check);

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

Incase all the answer given does not work, kindly try

String myString = null;

if(myString.trim().equalsIgnoreCase("null")){
    //do something
}

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

if (createReminderRequest.getDate() == null && createReminderRequest.getDate().trim().equals("")){
    DialogUtility.showToast(this, ProjectUtils.getString(R.string.please_select_date_n_time));
}

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())

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.

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);
    }

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


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-asynctask

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Android check null or empty string in Android java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState Android basics: running code in the UI thread How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? Android. Fragment getActivity() sometimes returns null android asynctask sending callbacks to ui AsyncTask Android example Return a value from AsyncTask in Android

Examples related to android-fragmentactivity

Manage toolbar's navigation and back button from fragment in android Android check null or empty string in Android Hide/Show Action Bar Option Menu Item for different fragments Android ViewPager with bottom dots How can I access getSupportFragmentManager() in a fragment? Default Activity not found in Android Studio startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment Setting Custom ActionBar Title from Fragment Start an activity from a fragment Android - Activity vs FragmentActivity?