Newaj
Newaj

Reputation: 4448

Retrieve data from several Firebase database reference at the same time in Android

I have several database references. From those, I'm fetching data & then keeping them in a list, example : List<Model>. I am using addValueEventListener() to retrieve data. Can I fetch all the data concurrently or I have to wait until completion of a single reference? What is the perfect way to do this?

Upvotes: 0

Views: 1493

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 139019

Adding a listener on the root reference, is a very bad idea because everytime something changes in your database, you'll need to download the entire JSON tree and this a waste of bandwidth and resources. To solve this, you can wait for the data that is coming from the database in order to create another query or you can use nested listeners. The nested listeners are a bit convoluted, but the flow itself should be pretty easy to follow. So in case of Firebase, there is nothing wrong about nested listeners.

What is the perfect way to do this?

The "perfect way" in this case, is the case that you are comfortable with.

Upvotes: 1

Janwilx72
Janwilx72

Reputation: 506

You can try something like this.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    ref.addValueEventListener(new ValueEventListener()
    {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
        {
            //Node 1: This let's you get data from the first node
            dataSnapshot.child("node1").getValue();

            //Node 2: This let's you get data from the second node
            dataSnapshot.child("node2").getValue();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

This way you use only 1 reference

Upvotes: 1

Related Questions