多横向RecyclerView重复数据问题:JSON解析与模型类适配求助
解决多个横向RecyclerView重复显示相同数据的问题
你遇到的问题根源很清晰——所有子RecyclerView显示重复数据,问题出在JSON解析过程中的列表引用复用上。
问题原因
你只初始化了一次singleItem列表,在遍历每个Section(也就是dataArray里的每个元素)时,没有重新创建新的列表实例,而是不断往同一个列表里追加数据,然后把这个列表的引用赋值给每个SectionDataModelSearch对象。这样所有Section最终都指向同一个数据集合,自然会显示全部数据的重复内容。
修复方案
在每次处理一个新的Section时,重新初始化singleItem列表,确保每个Section拥有独立的数据集合。
修正后的代码
try { JSONObject jsonObject = new JSONObject(jsonStr); JSONArray dataArray = jsonObject.getJSONArray("MyData"); for (int i = 0; i < dataArray.length(); i++) { JSONObject dataobj = dataArray.getJSONObject(i); String headerTitle = dataobj.getString("headerTitle"); JSONArray listViewData = dataobj.getJSONArray("listItem"); SectionDataModelSearch dm = new SectionDataModelSearch(); dm.setHeaderTitle(headerTitle); // 关键:在每个Section循环内重新初始化列表 List<SingleHandleSearchModel> singleItem = new ArrayList<>(); // 遍历当前Section的listItem数据 for (int j = 0; j < listViewData.length(); j++) { JSONObject c = listViewData.getJSONObject(j); String image = c.getString("image"); String name = c.getString("name"); singleItem.add(new SingleHandleSearchModel(name, image)); } dm.setAllItemsInSection(singleItem); allSampleData.add(dm); } } catch( final JSONException e){ Toast.makeText(getActivity(), "FAILED" + "Json parsing error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); }
说明
- 把
singleItem的初始化移到外层循环内部,这样每个Section都会创建一个全新的列表实例,数据不会互相覆盖。 - 确保每个
SectionDataModelSearch对象持有自己独立的子项列表,这样对应的横向RecyclerView就能加载各自Section的listItem数据了。
内容的提问来源于stack exchange,提问作者ANIMA SONGS
相关产品推荐
相关产品推荐

