1

Here is my json file

{
    status: true,
    version: "2.0.3",
    status_code: 200,
    expires: "1458121027.0",
    Etag: "1458121027.0",
    cache_key: "match|icc_wc_t20_2016_g14|overs_summary",
    data: {
        batting_order: [
            [
                "a",
                "1"
            ]
        ],
        innings: { }
    }
}

In which i was tried to get innings object of data object parent. It means data.innings

I put the condition like below

if(!data.isNull("innings") && data.has("innings")) {
    innings = data.getJSONObject("innings");
    inn_arr=innings.names(); 

    if (inn_arr.length() != 0) {//I got error over here.
        try {
            for (int i = 0; i < inn_arr.length(); i++) {
                if (inning_name.equals(inn_arr.getString(i))) {
                    inn_obj = innings.getJSONObject(inn_arr.getString(i));
                    if (inn_obj.has("overs_summary") && !inn_obj.isNull("overs_summary")) {
                        JSONArray over_summary = inn_obj.getJSONArray("overs_summary");
                        for (int j = over_summary.length() - 1; j >= 0; j--) {
                            JSONObject over_obj = over_summary.getJSONObject(j);
                            over_arr.add(over_obj);
                        }
                    }
                }
            }
        } catch (NullPointerException ne) {
            ne.printStackTrace();
        }
    }

}

In above code my app is crashed because of it not having the length.

Lux
  • 17,835
  • 5
  • 43
  • 73
Milan Gajera
  • 962
  • 2
  • 14
  • 41

2 Answers2

1

add if inn_arr is null

innings = data.getJSONObject("innings");
inn_arr = innings.names();
if (inn_arr != null && inn_arr.length() > 0) {
    //...
}

If you want to get key set from JSONObject then you can use two methods

  • innings.names() Returns an array containing the string names in this object. This method returns null if this object contains no mappings.

  • innings.keys() Returns an iterator of the String names in this object.

So you can use Iterator<String> iterator = innings.keys(); method and iterate over it to avoid NullPointerException.

Reference from this

Community
  • 1
  • 1
ELITE
  • 5,815
  • 3
  • 19
  • 29
1

Add a check(if (inn_arr != null)) whether inn_arr is null or not before if (inn_arr.length() != 0).

Febi M Felix
  • 2,799
  • 1
  • 10
  • 13