1

I have a database structure for chatting application so i have a message node in database looks like this enter image description here

messages is parent of a key the contains the UIDs of the two users chatting and this key contains the value of the chat body, I the application is working so far so good when pushing data done as i want.

But when trying to read the data the DataSnapShot object always have the the last leaf of the node means the child of the key. I tried different approaches to get the key it self to iterate through and get a list of its values with no luck.

Approach i tried

  public static final String MESSAGES_NODE_DB = "messages"; 
  mMessageDbRef = FirebaseDatabase.getInstance().getReference()
                    .child(MESSAGES_NODE_DB).child(keyUserA + "-" + KeyUserB);
    
     mMessageDbRef.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    Timber.d("parent key " + dataSnapshot.getKey());
    
                    for (DataSnapshot singleSnap : dataSnapshot.getChildren()) {
                            Message message = singleSnap.getValue(Message.class);
                            messageList.add(message);
                            instantiateRecyclerView();
                    }
                }

This approach always cause an error Can't convert object of type

java.lang.String

And parent key prints L91eMRVq_nx6WHUzZFo

Another one

    mMessageDbRef = FirebaseDatabase.getInstance().getReference().child("messages");
for (DataSnapshot singleSnap : dataSnapshot.getChildren()) {
                Timber.d("keys" + singleSnap.getKey());
            }
        }

The output is L91eMRVq_nx6WHUzZFo

What i want to achieve

To retrieve the list of keys inside of messages node as

vXgRtbjqhUYPOLyjhmGKRzITUC83-24L0kQx75fhoz06YpXnWRheETct2

Community
  • 1
  • 1
MuhammadAliJr
  • 273
  • 4
  • 17

2 Answers2

1

Inside onChildAdded method do not use getChildren() and the for loop method as the onChildAdded method returns the individual nodes below the mMessageDbRef reference. Basically the data snapshot parameter in onChildAdded can be converted to a Message object directly.

Thus, directly assign the data snapshot value to the message object as you have done without using any loop or the getChildren method.

And by doing this you will have access to the value of the message through the message object variables.

Something like this:

@Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                        Message message = dataSnapshot.getValue(Message.class);
                        messageList.add(message);
                        instantiateRecyclerView();
                }
            }
vivek verma
  • 1,716
  • 1
  • 17
  • 26
  • Indeed that worked thank you, though i'm creating another node for the users looks like this /users/{$userId}/value.. and i use the iteration on the node users and it get the children without any problem, can you help me explaining what's the difference? – MuhammadAliJr Apr 01 '18 at 21:02
  • what listener have you attached to the user node? is it childEventListener? – vivek verma Apr 02 '18 at 00:25
  • ValueEventListener That one, isn't suppose that the difference EventListener listen to a specific node, Why it behave differently? – MuhammadAliJr Apr 02 '18 at 08:22
1

To retrieve the key inside the messages node:

DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("messages").child(keyUserA + "-" + KeyUserB);

reference.addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
   String keys=datas.getKey();
    }
 }
 @Override
public void onCancelled(DatabaseError databaseError) {
   }
 });

the datasnapshot is on child(keyUserA + "-" + KeyUserB); then you iterate inside the randomid L91eMRVq_nx6WHUzZFo and you will be able to retrieve it using getKey()

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • The idea was to get the node containing the two uids and iterating through the snapshot will get me the childs of the pushed ids as vivek said, thanks for the comment though much appreciated. – MuhammadAliJr Apr 01 '18 at 20:59
  • iterating will get you this `L91eMRVq_nx6WHUzZFo` as explained, what ids do you want to get? – Peter Haddad Apr 01 '18 at 21:00
  • The question was about getting the direct child of messages node the long 2 string keys separated with "-" not the pushed ids inside them – MuhammadAliJr Apr 01 '18 at 21:05
  • then put the snapshot at `child("messages")` and iterate and use `getKey()` you will be able to get the list of keys seperated with "-" – Peter Haddad Apr 01 '18 at 21:06
  • I tried this approach and it was problematic too, let me update my question – MuhammadAliJr Apr 01 '18 at 21:15
  • that's weird, as it worked here: https://stackoverflow.com/questions/38232140/how-to-get-the-key-from-the-value-in-firebase – Peter Haddad Apr 01 '18 at 21:24
  • and here: https://stackoverflow.com/questions/42966179/getting-keys-from-firebase-query – Peter Haddad Apr 01 '18 at 21:25
  • and here also: https://stackoverflow.com/questions/42431858/getting-key-within-key-firebase – Peter Haddad Apr 01 '18 at 21:26
  • I looked for these answer before i post my question but it didn't work for me, i have no idea why even i checked my database and app logic more than once and can't find whats wrong. – MuhammadAliJr Apr 01 '18 at 21:46