点击用户行触发空指针异常,调试后仍未解决求助
问题分析与解决
这个空指针异常的核心原因是调用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
相关产品推荐
相关产品推荐

