java - 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
. 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:
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) {
}
});
}
解决方案
看到您的数据库架构和代码,我假设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);
推荐阅读
- c++ - 在 Visual Studio 2019 中使用 NuGet 填充 CMake 依赖项
- ansible - json_query 期间的 Ansible 'NoneType' 对象不可迭代”错误
- vue.js - 如何根据 VueJs 中按钮的 change\event 修改计算属性输出?
- json - 我在 Visual Studio 中的 package.json 中出现了一个我无法摆脱的随机 Debug
- python - 为什么在 255 倍时图片会变成紫色?
- logging - 间歇性气流日志丢失
- elixir - 映射 464360 个图像文件以读取和创建元组长生不老药
- python - 有时是列表,有时是字典
- git - 将 Visual Studio git 凭据存储在临时文件中
- if-statement - if 语句 TCL