I got a HttpResponse which gets a json response.
Now if the json response contains data it all works fine, but whenever the json is null my application crashes.
I've been trying to following code but with no avail.
(sb = json response)
Object result11 = sb;
Log.d("Result11", result11.toString());
if (result11 == JSONObject.NULL)
Log.d("if", "I am NULL");
else
Log.d("else", "I am not null");
I tried comparing result11 to:
null, "", "null", JSONObject.NULL
It always returns "I am not null"
Whilst the log says that Resul11 = null.
Any help would be appreciated. Thanks in advance.
EDIT:
Object result11 = sb;
Log.d("Result11", result11.toString());
StringBuilder test = (StringBuilder)result11;
if (test.toString().equals("null"))
Log.d("if", "I am NULL");
else
Log.d("else", "I am not null");
SOLUTION by @Mark Byers
test.toString().trim().equals("null")
results in "I AM NULL"
You don't have a null
. You have a StringBuilder
that when converted to a String
contains the value "null"
.
To compare strings do not use the ==
operator. Instead you should convert to a String
and use the equals
method.
StringBuilder stringBuilder = (StringBuilder)result11;
String trimmed = stringBuilder.toString().trim();
if (trimmed.equals("null")) { ... }
The ==
operator compares the references and only returns true if the operands are references to the same object (or both null references). The equals
method compares the values.
Related
如果你得到一个null结果与空指针比较: result11 == null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.