Firebase Strucutre

I am trying to retrieve Messages/child sorted on the base of time. I have access to Messages/child. I am unable to find any useful solution. Please help me figure this out.

My current code is:

FirebaseDatabase.getInstance()
    .getReference()
    .child("Messages")
    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
    .addChildEventListener(new ChildEventListener() {
          @Override
          public void onChildAdded(@NonNull DataSnapshot dataSnapshot,  @Nullable, String s) {

              Log.d("children",dataSnapshot.getKey());
              users_list.add(dataSnapshot.getKey());

          }

3 Answers

0
Sandeep Malik On

you can do this way :-

mChatReference = FirebaseDatabase.getInstance().getReference("Messages")
                .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        Query query = mChatReference.orderByChild("time");
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                   Log.d("children",dataSnapshot.getKey());
                users_list.add(dataSnapshot.getKey());            
            }

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

            }
        });
0
pratik vekariya On

Try this..

DocumentReference docRef = FirebaseFirestore.getInstance().collection(YOUR_COLLECTION).document(FirebaseAuth.getInstance().getCurrentUser().getUid());
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {

                if (document.contains("message")) {
                        String message=document.get("message").toString());
                    }
                //add other information to your user_list
            }
        }
    }
});
1
Frank van Puffelen On

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.