【问题标题】:Index 1 out of range [0..1) [closed]索引 1 超出范围 [0..1) [关闭]
【发布时间】:2020-01-20 11:15:08
【问题描述】:

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 循环而崩溃。那么当有数据可用时,app崩溃的原因是什么?

【问题讨论】:

标签: android arrays json


【解决方案1】:

索引总是从 0 开始。所以你在 for 循环中的条件应该是,

i rootCauseIdentificationArray.length()

不是这个,

i rootCauseIdentificationArray.length()

所以修改为,

for(int i = 0; i<rootCauseIdentificationArray.length(); i++)

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多