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
相关产品推荐
相关产品推荐

