【发布时间】:2017-10-12 16:06:46
【问题描述】:
我使用 Firebase 数据库并使用一个布尔字段将消息对象写入其中。当我尝试使用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"
}
该代码有什么问题?我试图弄清楚,但我仍然没有想出任何东西。
【问题讨论】:
-
你能分享一个 logcat 异常的例子吗?您的数据库中是否曾经出现过
isSent值不存在的情况(因此是null)? -
请在您发现异常的地方分享您的日志。
-
请截屏您的数据库控制台。
isSent字段可能不存在
标签: java android firebase firebase-realtime-database