You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:45:04