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

点击用户行触发空指针异常,调试后仍未解决求助

问题分析与解决

这个空指针异常的核心原因是调用equals()方法的对象为null——要么是chat.getReceiver()或chat.getSender()返回了null,要么是hisUid或firebaseAuth.getUid()为null,导致执行null.equals(xxx)时触发致命异常。你替换myUid为firebaseAuth.getUid()没用,是因为问题根源不在myUid的取值,而是某个参与比较的变量为null。

解决方案

有两种可靠的修复方式:

方式1:使用Objects.equals()方法(推荐)

Java的java.util.Objects类提供的equals()方法会自动处理null值,无需手动判空就能避免空指针。修改后的代码如下:

import java.util.Objects;

// ...

if (Objects.equals(chat.getReceiver(), firebaseAuth.getUid()) && Objects.equals(chat.getSender(), hisUid) ||
    Objects.equals(chat.getReceiver(), hisUid) && Objects.equals(chat.getSender(), firebaseAuth.getUid())) {
    chatList.add(chat);
}

方式2:手动判空+常量前置

如果不想引入Objects类,可以把确定不为null的变量放在equals()前面(比如确认firebaseAuth.getUid()和hisUid非空时),这样即使chat.getReceiver()或chat.getSender()为null,也只会返回false而不抛异常:

// 假设firebaseAuth.getUid()和hisUid已确保非空
if ((firebaseAuth.getUid().equals(chat.getReceiver()) && hisUid.equals(chat.getSender())) ||
    (hisUid.equals(chat.getReceiver()) && firebaseAuth.getUid().equals(chat.getSender()))) {
    chatList.add(chat);
}

如果hisUid或firebaseAuth.getUid()也可能为null,需要先加一层判空:

if (firebaseAuth.getUid() != null && hisUid != null && chat.getReceiver() != null && chat.getSender() != null) {
    if ((firebaseAuth.getUid().equals(chat.getReceiver()) && hisUid.equals(chat.getSender())) ||
        (hisUid.equals(chat.getReceiver()) && firebaseAuth.getUid().equals(chat.getSender()))) {
        chatList.add(chat);
    }
}

额外建议

  • 检查Chat类的getReceiver()和getSender()方法,确认是否会因为数据库字段为空等原因返回null。
  • 确认点击用户行时hisUid是否被正确赋值,避免出现null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:42:23