0

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.