notifyDataSetChanged не работает должным образом на фрагмент - PullRequest
0 голосов
/ 22 февраля 2019

Как описано в заголовке;Я не могу получить нужный фрагмент для правильного обновления.

У меня есть фрагмент, который показывает уведомления пользователю, и он должен обновляться каждый раз, когда документ добавляется в класс / базу данных.Однако, когда я удаляю документ вручную из базы данных, класс, кажется, не обновляется и показывает документы, ранее найденные в базе данных.Кроме того, он показывает текущие документы, если я открываю и закрываю приложение.

Фрагмент:

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

Ответы [ 2 ]

0 голосов
/ 23 февраля 2019

Используйте указанный ниже метод внутри вашего NotificationsAdapter.class, а затем вызовите этот метод вместо вызова notifyDataSetChanged () непосредственно в вашем фрагменте.На самом деле вы не передаете данные в адаптер, в котором возникла проблема.

public void updateAdapter(ArrayList<Notifications> mDataList) {
        this.mList = mDataList;
        notifyDataSetChanged();
    }
0 голосов
/ 22 февраля 2019

Если вы хотите удалить любой набор данных, вы должны установить 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 
...