如何从 Firebase 实时数据库中具有不同键的节点读取相同的值?

所以我试图在RecyclerView. 但是,我总是遇到无法读取正确值的问题,因为我不知道如何在键不同时输出正确的路径。

有人可以帮助我吗?

这是我在 Firebase 中的结构:

http://img4.mukewang.com/611e12250001914004490485.jpg

到目前为止,这是我的代码:


 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) {


            }

        });

    }


胡子哥哥
浏览 167回答 2
2回答

慕娘9325324

看到您的数据库架构和代码,我假设pollid您的参考中指定的变量包含LKwV ... IRyZ. 因此,要显示此节点内的所有评论,请使用以下代码行:DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();Query query = rootRef.child("comments").child(pollid).orderByChild("time");ValueEventListener valueEventListener = new ValueEventListener() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onDataChange(DataSnapshot dataSnapshot) {&nbsp; &nbsp; &nbsp; &nbsp; List<Comment> list = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; for(DataSnapshot ds : dataSnapshot.getChildren()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Comment comment = ds.getValue(Comment.class);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; commentList.add(comment);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //Do what you need to do with your list&nbsp; &nbsp; &nbsp; &nbsp; //Pass the list to the adapter and set the adapter&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onCancelled(@NonNull DatabaseError databaseError) {&nbsp; &nbsp; &nbsp; &nbsp; Log.d(TAG, databaseError.getMessage());&nbsp; &nbsp; }};query.addListenerForSingleValueEvent(valueEventListener);

Cats萌萌

尝试在您的查询中使用 orderByChild()。Query&nbsp;commentQuery&nbsp;=&nbsp;commentRef.limitToLast(mCurrentPage&nbsp;*&nbsp;TOTAL_ITEMS_TO_LOAD).orderByChild("time");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java