[英]How to read same value from nodes with different keys in Firebase real-time database?
So I'm trying to display a list of comments under a post in a RecyclerView
. 所以我试图在
RecyclerView
的帖子下显示评论列表。 However, I always run into the problem that I can't read the correct value because I don't know how to output the right path when the keys differ. 但是,我总是遇到无法读取正确值的问题,因为我不知道如何在键不同时输出正确的路径。
Can somebody help me? 有人能帮助我吗?
Here's my structure in Firebase: 这是我在Firebase中的结构:
Here's my code so far: 到目前为止,这是我的代码:
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) {
}
});
}
Seeing your database schema and your code, I assume that the pollid
variable specified in your reference holds the value of LKwV ... IRyZ
. 看到您的数据库模式和代码,我假设您的引用中指定的
pollid
变量保存LKwV ... IRyZ
的值。 So to display all the comments within this node, please use the following lines 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);
尝试在查询中使用orderByChild()。
Query commentQuery = commentRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD).orderByChild("time");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.