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?
You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.
The value 0 (all bits at zero) is a typical value used in memory to denote null . It means that there is no value associated with name . You can also think of it as the absence of data or simply no data.
The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.
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
From @Jon Skeet comment, really the String
value is "null"
. Following code solved it
if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With