java代码
try {
JSONObject res = new JSONObject(response);
if (res.getString("status").equalsIgnoreCase("success")) {
JSONObject obj = res.getJSONObject("data");
JSONArray rootCauseIdentificationArray = obj.getJSONArray("root_cause_identification");
//List<RootCauseIdentificationModel> tempList = new ArrayList<>();
for(int i = 0; i<=rootCauseIdentificationArray.length(); i++){
JSONObject objData = rootCauseIdentificationArray.getJSONObject(i);
//iterate the object here and add to the list
RootCauseIdentificationModel model = new RootCauseIdentificationModel( objData.getString("root_cause_identified"), objData.getString("solution_implemented"), objData.getString("implementaion_date"));
dataList.add(model);
}
stepsList.add(new TQMSavedDataModel(obj.getString("tangible_benefits"),
obj.getString("intangible_benefits"),
obj.getString("total_annual_savings"),
dataList));
}
} catch (JSONException e) {
e.printStackTrace();
dialog.dismiss();
Toast.makeText(getActivity(), "Something went wrong, please try again.", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
API
{
"status": "success",
"statuscode": 200,
"message": "Record found successfully.",
"data": {
"tangible_benefits": "ds1351gsghsdh353535535",
"intangible_benefits": "shwryw24y43rwehdg135313513",
"total_annual_savings": "45135432",
"root_cause_identification": [
{
"root_cause_identified": "efficiency",
"solution_implemented": "efficiency",
"implementaion_date": "14-01-2020"
}
]
}
}
正如您在此响应中看到的那样,响应“ root_cause_identification”中有一个数据,并且在解析响应时应用程序崩溃了一个FOR循环。那么,当有可用数据时,应用程序崩溃的原因是什么?
答案 0 :(得分:1)
索引始终从0开始。因此您在for循环中的条件应为
i << / strong> rootCauseIdentificationArray.length()
不是这个,
i <= rootCauseIdentificationArray.length()
因此将其修改为
for(int i = 0; i<rootCauseIdentificationArray.length(); i++)