Android中如何加载Firebase带随机key的评论子节点到RecyclerView
问题原因
你当前代码的核心错误是查询的数据库路径和实际存储的评论路径不匹配:
- 存储评论时的路径是
Comments/[当前新闻ID]/[随机评论key],对应新闻的评论都存在对应新闻ID的子节点下 - 但你构造FirebaseRecyclerOptions时,直接查询了
Comments根节点,这个节点下的直接子节点是各个新闻ID,不是你定义的Comment实体类结构,自然无法解析显示,也不会抛出错误。
修复方法
修改构造FirebaseRecyclerOptions的查询路径,指定到当前新闻ID对应的评论子节点即可,把原来的:
FirebaseRecyclerOptions<Comment> options = new FirebaseRecyclerOptions.Builder<Comment>() .setQuery(commentRef, Comment.class) .build();
改成:
FirebaseRecyclerOptions<Comment> options = new FirebaseRecyclerOptions.Builder<Comment>() // 新增.child(commentsID),查询当前新闻对应的评论节点 .setQuery(commentRef.child(commentsID), Comment.class) .build();
其他需要修复的问题
- 你在onCreate里重复调用了两次
recyclerView.setLayoutManager(layoutManager),删掉其中一次即可 - Comment实体类的无参构造方法是private,Firebase SDK反射解析实体类需要访问public的无参构造方法,这也是导致解析失败不显示的原因之一,把Comment类的:
改成private Comment() { }public Comment() { } - 建议把FirebaseRecyclerAdapter声明为Activity的全局成员变量,避免在onStart重复创建,也方便后续刷新数据
内容的提问来源于stack exchange,提问作者John Henry Elliot
相关产品推荐
相关产品推荐

