英文:
recyclerview uploads items multiple time on refresh
问题
我已经实现了一个RecyclerView,在其中我想展示应用程序中创建的群组。目前我正在使用swipeRefreshLayout刷新RecyclerView,但每次刷新RecyclerView时,它会根据刷新的次数多次打印出相同的群组。
有谁可以帮助我解决这个问题?
以下是代码部分。
onCreateView 方法:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    // ... (你的其他代码)
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            recyclerUpdater();
            swipeRefreshLayout.setRefreshing(false);
        }
    });
    return view;
}
recyclerUpdate 函数,用于向 RecyclerView 适配器中添加字符串:
private void recyclerUpdate() {
    if(user != null) {
        firebaseFirestore.collection("users").document(user.getUid()).collection("Groups").get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            mProjects.clear(); // 清空数据列表
                            mProjectsId.clear(); // 清空 ID 列表
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                String title = document.getString(TITLE);
                                String groupId = document.getString(GROUP_ID);
                                mProjects.add(title);
                                mProjectsId.add(groupId);
                            }
                            projectAdapter.setItems(mProjects, mProjectsId, getActivity());
                            projectAdapter.notifyDataSetChanged();
                            Log.d(TAG, "onComplete: list: " + mProjects.toString());
                        } else {
                            Log.d(TAG, "onComplete: error getting documents", task.getException());
                        }
                    }
                });
    }
}
这是 RecyclerView 适配器部分:
public class groupView extends RecyclerView.Adapter<groupView.ViewHolder> {
    // ... (你的其他代码)
    public void setItems(List<String> items, List<String> ids, Context context) {
        mItems = items;
        mIds = ids;
        mContext = context;
        notifyDataSetChanged(); // 更新数据后通知适配器更新UI
    }
    // ... (你的其他代码)
}
提前感谢你的帮助!
英文:
I have implemented a recyclerview, where I want to show the groups that have been created in the app. Right now I am refreshing the recyclerview using the swipeRefreshLayout, but everytime I refresh the recyclerview, it prints out the same group multiple times according to how many times I refresh it.
Can anyone help me solve this problem?
Below is the code.
onCreateView method:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    Log.d(TAG, "onCreateView: started");
    View view = inflater.inflate(R.layout.fragment_projects, container, false); //This inflates the project_fragment layout to this java class.
    swipeRefreshLayout = view.findViewById(R.id.swipeRefresh);
    add_btn = view.findViewById(R.id.add_project_btn);
    add_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            requestNewGroup();
        }
    });
    initRecyclerView(view);
    recyclerUpdater();
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            recyclerUpdater();
            swipeRefreshLayout.setRefreshing(false);
        }
    });
    return view;
}
recyclerUpdate function, where Strings are added to the recyclerView adapter:
 private void recyclerUpdate() {
    if(user != null) {
        firebaseFirestore.collection("users").document(user.getUid()).collection("Groups").get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                String title = document.getString(TITLE);
                                String groupId = document.getString(GROUP_ID);
                                mProjects.add(title);
                                mProjectsId.add(groupId);
                            }
                            projectAdapter.setItems(mProjects, mProjectsId, getActivity());
                            projectAdapter.notifyDataSetChanged();
                            Log.d(TAG, "onComplete: list: " + mProjects.toString());
                        } else {
                            Log.d(TAG, "onComplete: error getting documents", task.getException());
                        }
                    }
                });
    }
}
recyclerViewAdapter:
public class groupView extends RecyclerView.Adapter<groupView.ViewHolder>{
private static final String TAG = groupView.class.getSimpleName();
private List<String> mItems = new ArrayList<>();
private List<String> mIds = new ArrayList<>();
private Context mContext;
public void setItems(List<String> items, List<String> ids, Context context) {
    mItems = items;
    mIds = ids;
    mContext = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    if(viewType == 0){
        return ViewHolder.inflate(parent);
    }else{
        return null;
    }
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
    Log.d(TAG, "onBindViewHolder: called");
    if (holder instanceof ViewHolder) {
        ((ViewHolder) holder).bind(mItems.get(position));
        ((ViewHolder) holder).mLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: clicked on: " + mItems.get(position));
                //Sending ID as an intent, to be used in the process
                Intent intent = new Intent(mContext, projectClicked.class);
                intent.putExtra("itemPos", mItems.get(position));
                intent.putExtra("itemID", mIds.get(position));
                //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //close activitys before calling a new
                mContext.startActivity(intent);
            }
        });
    }
}
@Override
public int getItemCount() {
    return mItems.size();
}
@Override
public int getItemViewType(int position) {
    return 0;
}
static class ViewHolder extends RecyclerView.ViewHolder{
    private TextView mTextView;
    private LinearLayout mLinearLayout;
    public static ViewHolder inflate(ViewGroup parent) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem_group, parent,false);
        return new ViewHolder(view);
    }
    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        mTextView = itemView.findViewById(R.id.list_groups_title);
        mLinearLayout = itemView.findViewById(R.id.listitem_groups);
    }
    public void bind(String text){
        mTextView.setText(text);
    }
}
}
Thank you in advance!
答案1
得分: 0
你正在向 mProjects 和 mProjectsId 添加新项,而没有清空这些列表。
在 for 循环之前添加 clear():
if (task.isSuccessful()) {
    mProjects.clear();
    mProjectsId.clear();
    for (QueryDocumentSnapshot document : task.getResult()) {
        ...
英文:
You are adding new items to mProjects and mProjectsId not clearing these lists.
Add clear() before for loop:
if (task.isSuccessful()) {
   mProjects.clear();
   mProjectsId.clear();
   for (QueryDocumentSnapshot document : task.getResult()) {
   ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论