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?
Asked
Active
Viewed 1,252 times
0
-
Can you please show DB structure? – Janwilx72 Nov 04 '18 at 16:28
-
It's simple. A root reference having multiple nodes. All the nodes have similar type data (model) , but on different topics. That's why I'm maintaining separate nodes. – Newaj Nov 04 '18 at 16:36
2 Answers
1
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

Janwilx72
- 502
- 4
- 18
-
Then addValueEventListener() on every child nodes inside onDataChange()? – Newaj Nov 04 '18 at 16:48
-
You call ref once. Then in the onDataChange you can use the dataSnapshot to fetch data where you need. You can navigate to the Nodes you want by using the .child() after dataSnapshot. Then use the .getValue() to fetch the data. You don't need to add any more valueEventListeners. You can fetch all the data in 1 – Janwilx72 Nov 04 '18 at 17:41
1
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.

Alex Mamo
- 130,605
- 17
- 163
- 193
-
1
-
-
1I used a foreach loop for the nodes, there every node has several child nodes. There I populated the list again & again with data from every individual child nodes. – Newaj Nov 06 '18 at 10:10