As far as I can see you have a data structure:
Messages: {
uid1: {
uid2: {
messageId1: ...
messageId2: ...
messageId3: ...
}
}
}
You attach a ChildEventListener
to /Messages/uid1
, which means that your onChildAdded
gets called for user second-level UID from your JSON. To get to the individual messages, you still need to loop over the child nodes of the DataSnapshot
:
FirebaseDatabase.getInstance()
.getReference()
.child("Messages")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable, String s) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
Log.d("message key: ", messageSnapshot.getKey());
Log.d("message time: ", messageSnapshot.child("time").getValue(String.class));
}
}
A few things to note:
- As said, this code loops over the children of the
DataSnapshot
to get to the individual messages.
- Consider storing the data as chat rooms where the key of each chat room is based on the UID of its participants as explained here: Best way to manage Chat channels in Firebase
- You will need to add your messages to a list, and sort them client-side.
- You're storing the time as a display string, which makes it harder to sort them. Consider storing them in a format that is easier to sort, such as
"20190513T073306"
or a timestamp such as 1557758003677
.