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

Firebase数据库类型转换异常:Long转String失败排查求助

解决Firebase DatabaseException: Long转String失败的问题

这个报错com.google.firebase.database.DatabaseException: Failed to convert value of type java.lang.Long to String其实很明确——你的Firebase数据库里有字段存储的是Long类型的数字,但对应的Java模型类Notification里把这个字段定义成了String类型,导致Firebase在解析数据时无法完成类型转换,抛出异常。

问题定位

你的异常出现在这一行代码:

Notification notif=snapshot.getValue(Notification.class); //exception

Firebase尝试把数据库中Notifications/{userid}下的每条数据映射到Notification对象,但其中某一个字段(比如userid、postid或者text)在数据库里是数字类型(Long),而你在Notification类里把它声明成了String,所以转换失败。

解决方案

你有两种可行的解决思路,选哪种取决于你想保持数据库结构还是模型类结构:

方案1:修改Java模型类,匹配数据库字段类型

如果Firebase里的某个字段确实是Long类型(比如postid是数字ID),那直接把Notification类里对应的字段改成Long类型即可:

public class Notification {
    private String userid;
    private String text;
    private Long postid; // 把原来的String改成Long
    private boolean ispost;

    // 构造方法也要对应修改
    public Notification(String userid, String text, Long postid, boolean ispost) {
        this.userid = userid;
        this.text = text;
        this.postid = postid;
        this.ispost = ispost;
    }

    // getter和setter也要改成Long类型
    public Long getPostid() {
        return postid;
    }

    public void setPostid(Long postid) {
        this.postid = postid;
    }

    // 其他字段的代码保持不变
}

方案2:修正Firebase数据库中的数据类型

如果你想保持Notification类的字段都是String类型,那需要把Firebase数据库中所有对应字段的数值改成字符串格式(给数字加上引号)。比如原来的postid: 123要改成postid: "123",确保所有数据的类型和模型类一致。

额外建议

  • 最好的实践是数据库字段类型和Java模型类的字段类型完全一致,避免这类转换异常。
  • 如果不确定数据库里的字段类型,可以在Firebase控制台查看每条数据的字段标记(字符串会有引号,数字没有)。

内容的提问来源于stack exchange,提问作者Finga officiel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:26:29