Sagar Nayak Sagar Nayak - 5 months ago 7
Java Question

JSON object can not be inintialised

I am creating a

JSONObject
with the following code but the variable is showing
null
even after its initialization:

JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", "pradyut");
jsonObject.put("password", "5F4DCC3B5AA765D61D8327DEB882CF99");
} catch (JSONException e) {
e.printStackTrace();
Log.i("log", "json exception : " + e.toString());
}


if (jsonObject == null) {
Log.i("log", "the json object is not null");
// this part is showing everytime.
} else {
Log.i("log", "the json object is null");
}


I'm not getting any exception.

Why is that happening?

Answer

Your condition is wrong.

if (jsonObject == null) {
    Log.i("log", "the json object is not null");
    // this part is showing everytime.
} else {
    Log.i("log", "the json object is null");
}

jsonObject == null is checking if it's null. If it is true, it will go through the the block, else otherwise. I think you intend to reverse the condition.