Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Database NullPointerException when using getValue(Boolean.class) [duplicate]

I use Firebase Database and have message object written to it with one boolean field. When I try to read that object with getValue(Boolean.class) I get an exception. It only happens when getting this boolean value, I get string with no problem.

Method causing exception:

@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
}

My Message model class:

@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;
    }

}

Example of message stored in database:

{
  "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"
}

What is wrong with that code? I tried to figure it out but I still didn't come up with anything.

like image 812
fpiechowski Avatar asked Sep 24 '26 18:09

fpiechowski


1 Answers

Try to change isSent variable's type to Boolean.

It will help, in case when dataSnapshot.child("isSent").getValue(Boolean.class) returns null, cause reason of exception in calling method setSent(boolean) with null.

like image 131
Yegor Babarykin Avatar answered Sep 27 '26 09:09

Yegor Babarykin