I have to fetch all children data from firebase real time database? I want to fetch received messages of User2. How to do that? Database example is as given below -
Asked
Active
Viewed 1,433 times
0
-
1where is attached image ? – Ali Ahmed Sep 26 '18 at 12:10
-
I have added but can't see here. – sandy Sep 26 '18 at 12:12
-
add it again in edit. – Ali Ahmed Sep 26 '18 at 12:12
-
what you need to fetch from your image ? – Gastón Saillén Sep 26 '18 at 12:13
-
Hey I have edited the ques. Please suggest answer. – sandy Sep 26 '18 at 12:16
2 Answers
1
To be able to fetch the children data, try the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users").child("User1").child("MSG_TYPE_SENT");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String msgContent=datas.child("msgContent").getValue().toString();
String msgType=datas.child("msgType").getValue().toString();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
This will give you the msgContent
and the msgType
, to retrieve any data from the database, you need to pass through every node example:-
getReference("users").child("User1").child("MSG_TYPE_SENT");
Then you can loop inside the ids and retrieve the data.

Peter Haddad
- 78,874
- 25
- 140
- 134
-
Can we use map or any other thing to get children instead of using - getReference("users").child("User1").child("MSG_TYPE_SENT"); this?? because if there are number of children this way may be too lengthy. – sandy Sep 26 '18 at 12:41
-
you can add them in one child, `child("User1/MSG_TYPE_SENT")` anyway you should not nest the database alot, it should be flat database – Peter Haddad Sep 26 '18 at 12:45
0
Here you can fetch the User2 Messages Received
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");
mDatabase.child("User2").child("MSG_TYPE_RECEIVED").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot spanshot : dataSnapshot.getChildren()){
String content=snapshot.child("msgContent").getValue(String.class);
String type=snapshot.child("msgType").getValue(String.class);
//then you can log those values
Log.d("Values:",""+content+""+type);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
If the message received change at any time (lets say you want to implement the delete option in realtime of the message like whatsapp) .addValueEventListener
will update your UI in realtime if you have coded to show that the message has been deleted

Gastón Saillén
- 12,319
- 5
- 67
- 77