Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Snapshot listener to get real time update in a recyclerview?

Below is the code I used to retrieve documents data in a recyclerview. It works fine. But whenever the new document is added, it does not update it in real time. I know snapshot listener is for that purpose only but having a hard time to get it work. Any help will be appreciated. :)

 mFirestore.collection("Users").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()){
                    for (DocumentSnapshot document : task.getResult()) {
                        Message message = document.toObject(Message.class);
                        messageList.add(message);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
like image 342
Ashish Yadav Avatar asked Dec 07 '22 14:12

Ashish Yadav


1 Answers

you should separate the snapshot event like this.. then you can easily find out, what's the problem

mFirestore.collection("Users")
        .addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot snapshots,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Log.w("TAG", "listen:error", e);
                    return;
                }

                for (DocumentChange dc : snapshots.getDocumentChanges()) {
                    switch (dc.getType()) {
                        case ADDED:
                            Log.d("TAG", "New Msg: " + dc.getDocument().toObject(Message.class));
                            break;
                        case MODIFIED:
                            Log.d("TAG", "Modified Msg: " + dc.getDocument().toObject(Message.class));
                            break;
                        case REMOVED:
                            Log.d("TAG", "Removed Msg: " + dc.getDocument().toObject(Message.class));
                            break;
                    }
                }

            }
        });

Maybe the snapshot you got, was triggered by [MODIFIED] event, not [ADDED]..

like image 82
Howard Chen Avatar answered Dec 11 '22 10:12

Howard Chen