RecyclerView在刷新时多次上传项目。

huangapple go评论58阅读模式
英文:

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, &quot;onCreateView: started&quot;);
    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(&quot;users&quot;).document(user.getUid()).collection(&quot;Groups&quot;).get()
                .addOnCompleteListener(new OnCompleteListener&lt;QuerySnapshot&gt;() {
                    @Override
                    public void onComplete(@NonNull Task&lt;QuerySnapshot&gt; 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, &quot;onComplete: list: &quot; + mProjects.toString());
                        } else {
                            Log.d(TAG, &quot;onComplete: error getting documents&quot;, task.getException());
                        }
                    }
                });
    }
}

recyclerViewAdapter:

public class groupView extends RecyclerView.Adapter&lt;groupView.ViewHolder&gt;{

private static final String TAG = groupView.class.getSimpleName();
private List&lt;String&gt; mItems = new ArrayList&lt;&gt;();
private List&lt;String&gt; mIds = new ArrayList&lt;&gt;();
private Context mContext;

public void setItems(List&lt;String&gt; items, List&lt;String&gt; 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, &quot;onBindViewHolder: called&quot;);
    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, &quot;onClick: clicked on: &quot; + mItems.get(position));
                //Sending ID as an intent, to be used in the process
                Intent intent = new Intent(mContext, projectClicked.class);
                intent.putExtra(&quot;itemPos&quot;, mItems.get(position));
                intent.putExtra(&quot;itemID&quot;, 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

你正在向 mProjectsmProjectsId 添加新项,而没有清空这些列表。
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()) {
   ...

huangapple
  • 本文由 发表于 2020年10月17日 00:12:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64392776.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定