簡體   English   中英

notifyDataSetChanged在片段上無法正常工作

[英]notifyDataSetChanged not working properly on fragment

如標題中所述; 我發現自己無法獲得所需的片段以正確更新。

我有一個片段,向用戶顯示通知,並且每次將文檔添加到類/數據庫時都應該對其進行更新。 但是,當我從數據庫中手動刪除文檔時,該類似乎沒有更新,並且顯示了以前在數據庫中找到的文檔。 另外,如果我打開和關閉應用程序,它還會顯示當前文檔。

分段:

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;
}

數據庫結構:

數據庫結構

在NotificationsAdapter.class中使用下面給定的方法,然后調用此方法,而不是直接在Fragment中調用notifyDataSetChanged()。 實際上,您沒有將數據傳遞給問題的適配器。

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

如果要刪除任何數據集,則必須設置帶數據位置的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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM