2017-10-12 47 views
3

我使用Firebase数据库并使用一个布尔字段为其写入消息对象。当我尝试用getValue(Boolean.class)读取该对象时,我收到一个异常。它只发生在获得这个布尔值时,我得到没有问题的字符串。Firebase数据库使用getValue时的NullPointerException(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" 
} 

什么是错的代码?我试图弄清楚,但我仍然没有提出任何事情。

+0

你能分享的logcat例外的例子书面"sent" : true之前把@PropertyName("isSent")?在你的数据库中是否有一个case'isSent'值不存在(因此是'null')? – Grimthorr

+0

请在发生异常的地方分享您的日志。 – Sarfaraz

+0

请屏幕截图您的数据库控制台。领域'isSent'不存在 – faruk

回答

1

我使用布尔和从来都不是一个问题更换

public void setSent(boolean sent) { 

    isSent = sent; 
} 

。但我曾经遇到同样的问题,这是因为在数据库中它与字段sent保存而不是isSent。 你可以屏幕从你的控制台发射你的数据库吗?

我的解决方案是你的getter和setter

@PropertyName("isSent") 
public boolean isSent() { 

    return isSent; 
} 

@PropertyName("isSent") 
public void setSent(boolean sent) { 

    isSent = sent; 
} 

只怕你的数据库中的字段不"isSent" : true

3

试着改变isSent变量的类型为布尔

dataSnapshot.child("isSent").getValue(Boolean.class)返回空值时,将有助于调用方法setSent(boolean)null中的异常原因。

0

对我来说,它看起来像布尔(原始)和布尔(类)之间不匹配。你想解决这个问题,然后再试一次吗? 用布尔(类)替换消息模型类中的所有基元声明。 让我知道它是怎么回事。

0

尝试

public void setSent(boolean sent) { 

    this.isSent = sent; 
} 
相关问题