0

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"

Deejdd
  • 119
  • 1
  • 1
  • 8

2 Answers2

2

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

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Tried it but still results in not null. Also checked the webpage it reads it deffinitly says it's null, so does logcat. – Deejdd Dec 22 '12 at 12:36
  • I've added an explicit cast. If the type is wrong you should get an exception. – Mark Byers Dec 22 '12 at 12:39
  • Check my edit what I changed it to. It still results in I am not null =\ EDIT: I also added the stringbuilder to the log and results in printing null. – Deejdd Dec 22 '12 at 12:40
  • 1
    @Deejdd.. Seems like you have some unprintable characters or leading or trailing whitespaces in your string. Try using - `test.toString().trim().equals("null")`. This will only remove whitespaces if there are some. – Rohit Jain Dec 22 '12 at 12:43
  • Yes trimming worked ;), Marked as answer and added the solution to the main post. – Deejdd Dec 22 '12 at 12:45
0

if you get a null result compare to a null pointer: result11 == null

Henry
  • 42,982
  • 7
  • 68
  • 84