Laurynas G
Laurynas G

Reputation: 607

Handling null in JSONObject

My app uses Eventbrite API and it crashes when event logo is null.

JSONObject jsonRootObject = new JSONObject(event);
JSONArray jsonArray = jsonRootObject.optJSONArray("events");
JSONObject jsonObject = jsonArray.getJSONObject(i);
information = jsonObject.getJSONObject("logo");
text = information.getString("url");
name = "eventsImage" + i;
resId = getResources().getIdentifier(name, "id", getPackageName());
new LoadImagefromUrl().execute(new LoadImagefromUrlModel(text, resId));

I am trying to make exception for this event, but I am not very experienced with JSONObjects and I don't know how if statement should look like

I have tried the following, but it didn't work

jsonObject.getJSONObject("logo")!=null

Upvotes: 0

Views: 4107

Answers (2)

Shadab Ansari
Shadab Ansari

Reputation: 7070

You have to catch JSONException in

information = jsonObject.getJSONObject("logo");

like

try{
    information = jsonObject.getJSONObject("logo");
}catch(JSONException je){
    //json object not found
}

See this link

which says - public JSONObject getJSONObject (String name)

Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.

OR, You can use optJSONObject like this -

if(jsonObject.optJSONObject("logo")!=null)'

Because optJSONObject doesn't throws exceptions instead returns null if no key found

Upvotes: 4

Gennadii Saprykin
Gennadii Saprykin

Reputation: 4573

It crashes because you are trying to retrieve an object that does not exist. If object might be null you should be using jsonObject.optJsonObject("logo") instead.

Upvotes: 1

Related Questions