You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Retrofit加载双模型数据到ExpandableListView触发IndexOutOfBoundsException

问题排查与解决:ExpandableListView 填充数据触发 IndexOutOfBoundsException

以下是针对你遇到的问题的具体排查方向和解决建议:

1. 分组与子项数据数量不匹配

ExpandableListView 要求每个分组对应的子项列表必须合法存在(空列表也可,但不能为 null),如果适配器中返回的子项数量与实际数据不符,就会触发越界异常:

  • 检查 SubServiceAdapter 的 getChildrenCount(int groupPosition) 方法:确保返回对应分组下 ServicePriceList 的真实数量,比如正确写法应为:
    @Override
    public int getChildrenCount(int groupPosition) {
        List<ServicePriceList> childList = subServices.get(groupPosition).getServicePriceList();
        // 避免空列表导致的空指针,空列表返回0
        return childList != null ? childList.size() : 0;
    }
    
  • 确认 Retrofit 返回的每个 SubService 对象的 ServicePriceList 列表不为 null,可在数据解析后统一初始化空集合:
    List<SubService> subServices = response.body();
    for (SubService item : subServices) {
        if (item.getServicePriceList() == null) {
            item.setServicePriceList(new ArrayList<>());
        }
    }
    

2. 适配器数据更新时机错误

如果在数据未加载完成时就初始化适配器,或者更新数据后未通知适配器刷新,会导致适配器基于不完整/空数据计算索引:

  • 确保在 Retrofit 回调的 onResponse 方法内完成数据解析后,再初始化适配器并绑定到 ExpandableListView,必要时调用 adapter.notifyDataSetChanged() 刷新UI。
  • 禁止直接修改适配器内部的数据集合后不通知刷新,必须通过适配器的刷新方法同步UI状态。

3. 索引逻辑计算错误

检查适配器的 getGroup(int groupPosition) 和 getChild(int groupPosition, int childPosition) 方法,确保索引取值在合法范围内:

  • getGroup 需返回 subServices.get(groupPosition),且 groupPosition 必须小于 getGroupCount() 的返回值;
  • getChild 需返回 subServices.get(groupPosition).getServicePriceList().get(childPosition),且 childPosition 必须小于当前分组的 getChildrenCount(groupPosition) 返回值。

4. JSON数据结构验证

即使字段拼写正确,仍需确认返回的JSON结构是否符合预期:

  • 打印 Retrofit 返回的完整数据,检查是否存在某个 SubService 对应的 ServicePriceList 不是数组格式(比如是单个对象),导致解析后子项列表结构异常。

内容的提问来源于stack exchange,提问作者Mohammad khaled

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:10:51