簡體   English   中英

如何從Firebase實時數據庫中具有不同鍵的節點讀取相同的值?

[英]How to read same value from nodes with different keys in Firebase real-time database?

所以我試圖在RecyclerView的帖子下顯示評論列表。 但是,我總是遇到無法讀取正確值的問題,因為我不知道如何在鍵不同時輸出正確的路徑。

有人能幫助我嗎?

這是我在Firebase中的結構:

在此輸入圖像描述

到目前為止,這是我的代碼:

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

            }
        });
    }

看到您的數據庫模式和代碼,我假設您的引用中指定的pollid變量保存LKwV ... IRyZ的值。 因此,要顯示此節點中的所有注釋,請使用以下代碼行:

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

嘗試在查詢中使用orderByChild()。

Query commentQuery = commentRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD).orderByChild("time");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM