Search code examples
androidjsonfor-loopfacebook-graph-apijsonexception

For loop printing String only once when the condition is equal to 25


I'm trying to print out an object in the JSON using Facebook Graph API.

Here's my code:

try{
    JSONArray data = innerJson.getJSONArray("data");
    Log.d("innerDataLength", String.valueOf(data.length()));

    for (int i = 0; i<data.length(); i++) {
        String message = data.getJSONObject(i).getString("message");
        Log.d("message", message);
    }
} catch (JSONException e) {
    Log.d("exception", e.getMessage());
}

Here's output:

D/innerDataLength: 25
D/message: "blah blah blah"
D/exception: No value for message

As you can see the condition i.e. data.length() is 25 then why am I getting the message printed out only once?


Solution

  • Note that you get an exception:

    D/exception: No value for message

    It indicates that the second object in JSONArray has no message property. Looks like it's optional, so you need to check whether message property exists first.

    Update:

    try{
        JSONArray data = innerJson.getJSONArray("data");
        Log.d("innerDataLength", String.valueOf(data.length()));
    
        for (int i = 0; i < data.length(); i++) {
            JSONObject obj = data.getJSONObject(i);
            if (obj.has("message")) {
                String message = obj.getString("message");
                Log.d("message", message);
            }
            if (obj.has("story")) {
                String story= obj.getString("story");
                Log.d("story", story);
            }
        }
    } catch (JSONException e) {
        Log.d("exception", e.getMessage());
    }