Java – How do I read the same value from nodes with different keys in the Firebase real-time database?

How do I read the same value from nodes with different keys in the Firebase real-time database?… here is a solution to the problem.

How do I read the same value from nodes with different keys in the Firebase real-time database?

So I’m trying to show a list of comments under posts in RecyclerView. However, I always have the problem of not being able to read the correct value because I don’t know how to output the correct path when the keys are different.

Can someone help me?

This is my structure in Firebase:

enter image description here

So far, here’s my code:

 private void loadComments() {
        DatabaseReference commentRef = mRootReference.child("comments").child(pollid).getParent().child("comment");
        Query commentQuery = commentRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);
        commentQuery.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    Comment comment = ds.getValue(Comment.class);
                    commentList.add(comment);
                    mAdapter.notifyDataSetChanged();
                    mCommentList.scrollToPosition(commentList.size() - 1);
                }
            }

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

}

@Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

}

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

}

@Override
            public void onCancelled(DatabaseError databaseError) {

}
        });
    }

Solution

Looking at your database schema and code, I assume that the pollid variable specified in your reference contains LKwV... The value of IRyZ. Therefore, to display all comments within that node, use the following line of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("comments").child(pollid).orderByChild("time");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<Comment> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Comment comment = ds.getValue(Comment.class);
            commentList.add(comment);
        }

Do what you need to do with your list
        Pass the list to the adapter and set the adapter
    }

@Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

Related Problems and Solutions