java - 如何解决recyclerview中的重复数据

标签 java android android-recyclerview

检索数据时,我在 RecyclerView 中收到重复的数据项。

我尝试过一些类似的方式NotifyDataSetChanged()setHasStableIds (true)。但仍然没有成功,我尝试了这种方式( How to solve duplicate data items in recyclerview )但仍然没有成功。

private void loadFirstPage() {
    Log.d(TAG, "loadFirstPage: ");

    callTopRatedMoviesApi().enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            if (!response.isSuccessful()) {
                Log.e(TAG, "Response Error : " + response.code());
            } else {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    JSONArray itemsObject = dataObject.getJSONArray("items");
                    modelGetProductSearchList = new ArrayList<>();
                    progressBar.setVisibility(View.GONE);

                    if (itemsObject.length() == 0) {
                        // Set GONE Visibility of TextView
                    } else {
                        for (int a = 0; a <= itemsObject.length(); a++) {
                            JSONObject object = itemsObject.getJSONObject(a);
                            ModelGetProductSearch modelGetProductSearch = new ModelGetProductSearch();
                            modelGetProductSearch.setId(object.getInt("id"));
                            modelGetProductSearch.setName(object.getString("name"));

                            JSONObject sourceObject = object.getJSONObject("source");
                            modelGetProductSearch.setSourceNames(sourceObject.getString("name"));

                            modelGetProductSearchList.add(modelGetProductSearch);
                            adapter.addAll(modelGetProductSearchList);
                            progressBar.setVisibility(View.GONE);
                            tvTidakAdaHasil.setVisibility(View.GONE);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (currentPage <= TOTAL_PAGES && currentPage <= adapter.getItemCount()) adapter.addLoadingFooter();
                else isLastPage = true;
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.getMessage());
            tvTidakAdaHasil.setText("Maaf, cek koneksi internet anda dan coba kembali");
            progressBar.setVisibility(View.GONE);
        }
    });
}

private void loadNextPage() {
    Log.d(TAG, "loadNextPage: " + currentPage);

    callTopRatedMoviesApi().enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            adapter.removeLoadingFooter();
            isLoading = false;

            if (!response.isSuccessful()) {
                Log.e(TAG, "Response Error : " + response.code());
            } else {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    JSONArray itemsObject = dataObject.getJSONArray("items");
                    modelGetProductSearchList = new ArrayList<>();
                    progressBar.setVisibility(View.GONE);

                    for (int a = 0; a <= itemsObject.length(); a++) {
                        JSONObject object = itemsObject.getJSONObject(a);
                        ModelGetProductSearch modelGetProductSearch = new ModelGetProductSearch();
                        modelGetProductSearch.setId(object.getInt("id"));
                        modelGetProductSearch.setName(object.getString("name"));

                        JSONObject sourceObject = object.getJSONObject("source");
                        modelGetProductSearch.setSourceNames(sourceObject.getString("name"));

                        modelGetProductSearchList.add(modelGetProductSearch);
                        adapter.addAll(modelGetProductSearchList);
                        progressBar.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (currentPage != TOTAL_PAGES && currentPage <= adapter.getItemCount()) adapter.addLoadingFooter();
                else isLastPage = true;
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.getMessage());
            tvTidakAdaHasil.setText("Maaf, cek koneksi internet anda dan coba kembali");
            progressBar.setVisibility(View.GONE);
        }
    });
}

这是我的适配器

public class AdapterDetailSearch extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int ITEM = 0;
    private static final int LOADING = 1;

    private List<ModelGetProductSearch> modelGetProductSearchList;
    private Context context;

    private boolean isLoadingAdded = false;

    public AdapterDetailSearch(Context context) {
        this.context = context;
        modelGetProductSearchList = new ArrayList<>();
    }

    public List<ModelGetProductSearch> getMovies() {
        return modelGetProductSearchList;
    }

    public void setMovies(List<ModelGetProductSearch> movieResults) {
        this.modelGetProductSearchList = movieResults;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        switch (viewType) {
            case ITEM:
                viewHolder = getViewHolder(parent, inflater);
                break;
            case LOADING:
                View v2 = inflater.inflate(R.layout.row_item_progress, parent, false);
                viewHolder = new LoadingVH(v2);
                break;
        }
        return viewHolder;
    }

    @NonNull
    private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
        RecyclerView.ViewHolder viewHolder;
        View viewHolder = inflater.inflate(R.layout.row_item_detail_list, parent, false);
        return new MovieVH(viewHolder);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {

        final ModelGetProductSearch result = modelGetProductSearchList.get(position);

        switch (getItemViewType(position)) {
            case ITEM:
                final MovieVH itemsListVH = (MovieVH) holder;

                // Visible and Invisible set TextView
        }
    }

    @Override
    public int getItemCount() {
        return modelGetProductSearchList == null ? 0 : modelGetProductSearchList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return (position == modelGetProductSearchList.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
    }


   /*
   Helpers
   _________________________________________________________________________________________________
   */

    public void add(ModelGetProductSearch r) {
        modelGetProductSearchList.add(r);
        notifyItemInserted(modelGetProductSearchList.size() - 1);
    }

    public void addAll(List<ModelGetProductSearch> moveResults) {
        for (ModelGetProductSearch result : moveResults) {
            add(result);
        }
    }

    public void remove(ModelGetProductSearch r) {
        int position = modelGetProductSearchList.indexOf(r);
        if (position > -1) {
            modelGetProductSearchList.remove(position);
            notifyItemRemoved(position);
        }
    }

    public void clear() {
        isLoadingAdded = false;
        while (getItemCount() > 0) {
            remove(getItem(0));
        }
    }

    public boolean isEmpty() {
        return getItemCount() == 0;
    }


    public void addLoadingFooter() {
        isLoadingAdded = true;
        add(new ModelGetProductSearch());
    }

    public void removeLoadingFooter() {
        isLoadingAdded = false;

        int position = modelGetProductSearchList.size() - 1;
        ModelGetProductSearch result = getItem(position);

        if (result != null) {
            modelGetProductSearchList.remove(position);
            notifyItemRemoved(position);
        }
    }

    public ModelGetProductSearch getItem(int position) {
        return modelGetProductSearchList.get(position);
    }


   /*
   View Holders
   _________________________________________________________________________________________________
   */

    /**
     * Main list's content ViewHolder
     */
    protected class MovieVH extends RecyclerView.ViewHolder {
        private LinearLayout llContainer;
        private ImageView ivItem;
        private TextView tvItemTitle, tvPriceRegular, tvPriceAfterDiscount, textFrom;

        public MovieVH(View itemView) {
            super(itemView);

            llContainer = itemView.findViewById(R.id.container);
            ivItem = itemView.findViewById(R.id.iv_item);
            textFrom = itemView.findViewById(R.id.tv_from);
        }
    }


    protected class LoadingVH extends RecyclerView.ViewHolder {
        public LoadingVH(View itemView) {
            super(itemView);
        }
    }
}

最佳答案

您在适配器中的for-loop内多次添加相同的列表,这就是它创建重复的原因。将 adapter.addAll 移到 for 循环 之外,如下所示:

if (itemsObject.length() == 0) {
    // Set GONE Visibility of TextView
} else {
    for (int a = 0; a < itemsObject.length(); a++) {
        ...

        //Remove from here
        /*adapter.addAll(modelGetProductSearchList);
        progressBar.setVisibility(View.GONE);
        tvTidakAdaHasil.setVisibility(View.GONE);*/    
    }

    //Add list here
    adapter.addAll(modelGetProductSearchList);
    progressBar.setVisibility(View.GONE);
    tvTidakAdaHasil.setVisibility(View.GONE);
}

关于java - 如何解决recyclerview中的重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60294438/

相关文章:

java - 签名的小程序被反向代理 ('Unknown Source' 阻止在网络浏览器上)

android - 如何通过单击按钮从大约返回到上一个 Activity ?

android - 嵌套的 RecyclerView 的高度为 “wrap_content”,包含大量项目

java - 来自 InputStream 的编年史字节

java - 将 Jenkins 工作指定为仅运行一个分支?

java - 有人可以帮助我理解调用 Intent 来选择文件吗?

android - 一些 Youtube 视频显示在 RecyclerView 中

java - 在 RecyclerView 中重置先前 CardView 的颜色

java - 小于运算符也评估相等值

android - 如何在PagerSlidingTabStrip中将标签切换到指定位置