RecyclerView加载网络JSON数据重复问题及代码求助
解决RecyclerView列表内容重复的问题
看起来你的问题主要出在接口请求参数格式错误和滚动监听未做防重复请求处理上,这导致每次加载更多时都重复添加了相同的数据——而ListView可能因为触发逻辑不同,暂时没暴露这个问题。下面一步步帮你解决:
1. 修复URL参数格式错误
你当前的请求URL拼接有问题:
"https://raw.githubusercontent.com/abodali/ox/master/f.txt?limit" + limit
这里缺少了参数的等于号,会生成类似?limit0、?limit10的无效格式,后端根本识别不到正确的limit参数,所以每次请求都会返回全部数据,自然会重复添加到listItems里。
修改为正确的参数格式:
"https://raw.githubusercontent.com/abodali/ox/master/f.txt?limit=" + limit
2. 添加加载中标志位,防止重复触发请求
快速滑动RecyclerView时,当前的滚动监听可能会多次触发加载逻辑,导致同一批数据被重复请求和添加。我们可以加一个布尔变量标记加载状态,避免重复请求:
首先在类中添加状态变量:
private boolean isLoading = false;
然后修改滚动监听逻辑:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { // 仅在向上滑动且未处于加载状态时判断 if (dy > 0 && !isLoading) { int lastVisibleItem = gridLayoutManager.findLastCompletelyVisibleItemPosition(); if (lastVisibleItem == listItems.size() - 1) { isLoading = true; // 标记为加载中,避免重复触发 Get_All_Users(listItems.get(listItems.size()-1).getId()); } } } });
最后在请求回调中重置加载状态:
// 成功回调中 @Override public void onResponse(String response) { try { JSONArray jsonArray = new JSONArray(response); JSONObject jsonResponse = jsonArray.getJSONObject(0); JSONArray jsonArray_usersS = jsonResponse.getJSONArray("All_storys"); for (int i = 0; i < jsonArray_usersS.length(); i++) { JSONObject responsS = jsonArray_usersS.getJSONObject(i); int id = responsS.getInt("id"); String story = responsS.getString("story_name"); String img_link = responsS.getString("img_link"); listItems.add(new List_Item(id, story, img_link)); } recyclerView_dAdapter.notifyDataSetChanged(); isLoading = false; // 加载完成,允许下次请求 } catch (JSONException e) { e.printStackTrace(); isLoading = false; // 出错也要重置状态 } } // 错误回调中 @Override public void onErrorResponse(VolleyError error) { isLoading = false; }
3. 优化RecyclerView刷新方式(可选)
用notifyDataSetChanged()会刷新整个列表,性能较差。如果知道新添加的数据条数,可以用局部刷新提升性能:
int newItemCount = jsonArray_usersS.length(); int startPosition = listItems.size() - newItemCount; recyclerView_dAdapter.notifyItemRangeInserted(startPosition, newItemCount);
做完这些修改后,RecyclerView的重复加载问题应该就能解决了。
内容的提问来源于stack exchange,提问作者Obeda Al Ale
相关产品推荐
相关产品推荐

