Kavin Raju S
Kavin Raju S

Reputation: 1382

Firebase - Firestore data query callled twice two times

I have a code that needs to update the UI with all the data in Cloud Firestore, under a collection, then need to update the UI when an item is added. I have used Recycler to add more data:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_events);
    ButterKnife.bind(this);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

collection_events
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() 
{
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot snapshot: 
Objects.requireNonNull(task.getResult())){
                            EventsCurrent eventsCurrent = 
snapshot.toObject(EventsCurrent.class);
                            eventsCurrent.setId(snapshot.getId());
                            Log.d(TAG,snapshot.getId());
                            eventsCurrentList.add(eventsCurrent);
                        }
                        LinearLayoutManager linearLayoutManager = new 
LinearLayoutManager(getApplicationContext());
                        eventsAdapter = new 
EventsAdapter(EventsActivity.this,eventsCurrentList);
                        eventsAdapter.setEventsCurrents(eventsCurrentList);

recylerview_events.setLayoutManager(linearLayoutManager);
                        recylerview_events.setHasFixedSize(true);
                        recylerview_events.setAdapter(eventsAdapter);
                        isFirstTime = false;
                    }else {
                        Log.d(TAG, "Error getting documents: ", 
task.getException());
                    }
                }
            });


    db.collection("current_events")
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot 
queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
                        Log.w(TAG, "listen:error", e);
                        return;
                    }
                    for(DocumentChange dc: 
queryDocumentSnapshots.getDocumentChanges()){
                        switch (dc.getType()){
                            case ADDED:
                                if (!isFirstTime) {

eventsAdapter.addEvent(dc.getDocument().toObject(EventsCurrent.class));

eventsAdapter.notifyItemInserted(eventsAdapter.numberOfevents());
                                }
                                break;
                            case MODIFIED:
                                eventsAdapter.notifyDataSetChanged();
                                break;
                        }
                    }

                }
            });
}

Here I am using both get() & addSnapshotListener() so that I initially get all the data via get() and the updated or added data via addSnapshotListener().

The issue both the listener gets called and my data becomes doubled and the data are populated twice.

Could anyone please help me out?

Upvotes: 3

Views: 4272

Answers (2)

Fateh Singh Saini
Fateh Singh Saini

Reputation: 129

I am having same issue, i was solving this issue by using 'return@addSnapshotListener' in end of method call.

 mFirebaseFireStore.collection(AppConstant.FIREBASE_USER_TABLE).document(key).addSnapshotListener {result,error ->
    if(result==null){
       error?.message?.let { it1 -> Log.w("Error-Group", it1)
    }
           return@addSnapshotListener
        }

    if(result.exists())
      {
        //some code
      }
    return@addSnapshotListener
 }

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138824

The issue both the listener gets called and my data becomes doubled and the data are populated twice.

This is happening because you are using get() & addSnapshotListener() to get the data at the same time. What actually means is that you are getting the data from the database once and second, you are getting the data again but in real-time and that's why your data becomes doubled. If you want to get the data in real-time, only use addSnapshotListener(). If you want to get it only once, just use a get() call. Both methods have the same behavior but in the case of addSnapshotListener(), the listener remains active until you remove it.

Upvotes: 4

Related Questions