Java 使用getValue(Boolean.class)时Firebase数据库NullPointerException
我使用Firebase数据库,并使用一个布尔字段将消息对象写入其中。当我试图用Java 使用getValue(Boolean.class)时Firebase数据库NullPointerException,java,android,firebase,firebase-realtime-database,Java,Android,Firebase,Firebase Realtime Database,我使用Firebase数据库,并使用一个布尔字段将消息对象写入其中。当我试图用getValue(Boolean.class)读取该对象时,我得到一个异常。只有当得到这个布尔值时才会发生,我得到的字符串没有问题 导致异常的方法: @Override public void onDataChange(DataSnapshot dataSnapshot) { message.setSenderId(dataSnapshot.child("senderId").getValue
getValue(Boolean.class)
读取该对象时,我得到一个异常。只有当得到这个布尔值时才会发生,我得到的字符串没有问题
导致异常的方法:
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
message.setSenderId(dataSnapshot.child("senderId").getValue(String.class));
message.setDestinationId(dataSnapshot.child("destinationId").getValue(String.class));
message.setDatetime(dataSnapshot.child("datetime").getValue(Date.class));
message.setText(dataSnapshot.child("text").getValue(String.class));
message.setSent(dataSnapshot.child("isSent").getValue(Boolean.class)); // this line causes NullPointerException
}
我的消息模型类:
@IgnoreExtraProperties
public class Message {
@Exclude
private String id;
@Exclude
private ValueEventListener valueListener;
@Exclude
private Conversation destination;
// User ID
private String senderId;
// Conversation ID
private String destinationId;
private Date datetime;
private String text;
private boolean isSent = false;
public Message(String id, String sender, String destination, Date date, String text) {
this.id = id;
this.senderId = sender;
this.destinationId = destination;
this.datetime = date;
this.text = text;
}
public Message() {
}
public Message(String id, Conversation destination) {
this.id = id;
this.destination = destination;
}
// ...
public boolean isSent() {
return isSent;
}
public void setSent(boolean sent) {
isSent = sent;
}
}
存储在数据库中的消息示例:
{
"datetime" : {
"date" : 12,
"day" : 4,
"hours" : 17,
"minutes" : 32,
"month" : 9,
"seconds" : 25,
"time" : 1507822345776,
"timezoneOffset" : -120,
"year" : 117
},
"destinationId" : "test_conversation",
"isSent" : true,
"senderId" : "test_sender",
"text" : "hello world"
}
那个代码有什么问题?我试图弄明白,但仍然没有想出任何办法。尝试将isSent变量的类型更改为布尔值
如果
dataSnapshot.child(“isSent”).getValue(Boolean.class)
返回null,则会有帮助,因为调用方法setSent(Boolean)
时出现异常,在我看来,Boolean(原语)和Boolean(类)之间似乎不匹配。是否要修复该问题并重试?
将消息模型类中的所有基元声明替换为Boolean(类)。
让我知道情况。尝试更换
public void setSent(boolean sent) {
isSent = sent;
}
与
我用的是布尔运算,从来都不是问题。但我曾经遇到过同样的问题,因为在数据库中,它使用字段
sent
而不是isSent
保存。
你能从你的控制台截图你的数据库吗
我的解决方案是将@PropertyName(“isSent”)
放在getter和setter之前
@PropertyName("isSent")
public boolean isSent() {
return isSent;
}
@PropertyName("isSent")
public void setSent(boolean sent) {
isSent = sent;
}
很抱歉,您数据库中的字段被写入了
“sent”:true
而不是“isSent”:true
您能分享一个来自logcat的异常示例吗?您的数据库中是否存在isSent
值不存在的情况(因此null
)?请在出现异常的地方共享日志。请在数据库控制台上截屏。可能字段isSent
不存在
@PropertyName("isSent")
public boolean isSent() {
return isSent;
}
@PropertyName("isSent")
public void setSent(boolean sent) {
isSent = sent;
}