notifyDataSetChanged在片段上无法正常工作

问题描述 投票:0回答:2

如标题中所述;我发现自己无法正确更新所需的片段。

我有一个向用户显示通知的片段,每次将文档添加到类/数据库时都应该更新它。但是,当我从数据库中手动删除文档时,该类似乎没有更新,它显示以前在数据库中找到的文档。此外,如果我打开和关闭应用程序,它会显示当前文档。

分段:

public class NotificationFragment extends android.support.v4.app.Fragment {

private RecyclerView mNotificationList;
private NotificationsAdapter notificationsAdapter;
private List<Notifications> mNotifList;
private FirebaseFirestore mFirestore;


public NotificationFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_notification, container, false);


    mNotifList = new ArrayList<>();

    mNotificationList = (RecyclerView) v.findViewById(R.id.notification_list);
    notificationsAdapter = new NotificationsAdapter(getContext(), mNotifList);


    mNotificationList.setHasFixedSize(true);
    mNotificationList.setLayoutManager(new LinearLayoutManager(container.getContext()));
    mNotificationList.setAdapter(notificationsAdapter);

    mFirestore = FirebaseFirestore.getInstance();

    String current_user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();

    mFirestore.collection("Users").document(current_user_id).collection("Notifications").addSnapshotListener(requireActivity(), new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
            if (documentSnapshots != null && !documentSnapshots.isEmpty()) {
                for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
                    if (doc.getType() == DocumentChange.Type.ADDED) {
                        Notifications notifications = doc.getDocument().toObject(Notifications.class);
                        mNotifList.add(notifications);
                        notificationsAdapter.notifyDataSetChanged();

                    }
                }

            }
        }
    });


    return v;
}

数据库结构:

Database Structure

java android android-fragments google-cloud-firestore notifydatasetchanged
2个回答
1
投票

在NotificationsAdapter.class中使用下面给出的方法,然后调用此方法,而不是直接在Fragment中调用notifyDataSetChanged()。实际上,您没有将数据传递给适配器,这是问题所在。

public void updateAdapter(ArrayList<Notifications> mDataList) {
        this.mList = mDataList;
        notifyDataSetChanged();
    }

0
投票

如果要删除任何数据集,则必须使用数据位置设置notifyItemRemoved。

例:

mDataset.remove(position); // remove your data
notifyItemRemoved(position); // notify that your data is removed
notifyItemRangeChanged(position, mDataSet.size()); // you can use if range is changed 
© www.soinside.com 2019 - 2024. All rights reserved.