ANDROID :从 volley 请求填充回收器视图的更好方法,GETS DUPLICATE

ANDROID : better way of populating a recycler view from volley request, GETS DUPLICATE

我的截击请求有效,但我遇到了这个问题。

如下图是我典型的截击请求。这是从 table 中获取行并将它们显示在带有卡片视图的回收视图中。

我已经把整个过程写成一个方便回忆的方法。 我在工具栏的 'Refresh' 按钮中调用该方法。当我碰巧在第一个请求尚未完成之前多次单击它时,卡片视图会重复,就好像这些行被请求了两次一样。好吧,该方法被调用了两次。我想如果我把 new ArrayList<>();方法开始时的问题应该可以解决,但我错了。

这是我认为会发生的情况。

1. load() is called. 2. new instance of myList is created. 3. first request is sent. 4. load() is called again. 5. new instance of myList is created. 6. second request is sent. 7. first request returns json. 8. parses and adds to second myList instance. 9. second request returns json. 10. parses and adds to myList instance.

这是我的典型截击请求。

// List<Objectbuilder> myList; is declared in class.


private void load(){
    myLIST= new ArrayList<>();
    RequestQueue requestQueue = Volley.newRequestQueue(TeacherEditQuizQuestionList.this);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("RESULT");

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    String tempCOL1 = jsonObject1 .getString("COL1");
                    String tempCOL2 = jsonObject1 .getString("COL2");
                    String tempCOL3 = jsonObject1 .getString("COL3");

                    Objectbuilder newobject = newObjectbuilder(tempCOL1 ,tempCOL2 ,tempCOL3 );

                    myLIST.add(ql_newobject );
                }
                adapter recycler_adapter = new adapter(Activity.this,myLIST);
                recycler_display.setAdapter(ql_adapter );
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

                Toast.makeText(Activity.this, ""+error, Toast.LENGTH_SHORT).show();
        }
    })
    };

    requestQueue.add(stringRequest);
}

该方法应用于 OnCreate 和工具栏上的 "Refresh" 按钮。如果我点击刷新按钮的速度太快或重复点击,卡片视图将显示为

        [Row1 info            ]
        [Row2 info            ]
        [Row3 info            ]
        [Row1 info            ]
        [Row2 info            ]
        [Row3 info            ]

我的意思是,没那么麻烦。如果我单击一次刷新按钮并耐心等待,它将自行重置并正常显示正确的行数并且没有重复。我只是去了这里,以防万一可能有更好的方法来做到这一点。也许我可以从你们那里学到一个拯救这个项目和这个学期的救生技巧哈哈。

创建一个 onResponse 的本地列表,并用您的响应数据填充该列表。当完全填充并准备好应用到您的适配器时,您然后创建或清除 myLIST 并填写它。两个未完成的 load 调用将在他们需要的时候分配执行此操作(在onResponse 处理程序)。响应处理程序不应相互抢占,最后一个分配(或清除)myLIST 获胜。如果 Response 处理程序有可能相互抢占,则添加一些同步(但不是必需的)。