Java – Firebase database NullPointerException when using getValue(Boolean.class).

Firebase database NullPointerException when using getValue(Boolean.class)…. here is a solution to the problem.

Firebase database NullPointerException when using getValue(Boolean.class).

I use a Firebase database and write message objects to it using a boolean field. When I try to read the object using getValue(Boolean.class), I get an exception. It only happens when I get this boolean value, I can get the string without any problem.

Method that causes the 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 a message stored in a 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’s wrong with this code? I tried to figure it out, but I still haven’t figured out anything.

Related Problems and Solutions