Android check null or empty string in Android

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

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? Thanks in advance.

回答1:

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.


回答2:

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

if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null"))  


回答3:

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


回答4:

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.



回答5:

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


回答6:

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


回答7:

WORKING !!!!

    String text = mEmailTextView.getText().toString();     if (text.matches("")&& text.trim().equals("null")){          return false;     }     else{         return true;     } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!