0

Snapshot.getValue is producing null pointer exception,how should i solve this error?

DatabaseReference offsetRef = FirebaseDatabase.getInstance().getReference(".info/serverTimeOffset");
        offsetRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                double offset = snapshot.getValue(Double.class);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
akash sharma
  • 13
  • 1
  • 5
  • It sounds like `.info/serverTimeOffset` may not exist, which means that the `Double` you get out of it is `null`, which can't be unboxed. The solution would be to make the type `Double offset = ...` or to unbox after checking for `null`. See https://stackoverflow.com/questions/2382058/unboxing-null-object-to-primitive-type-results-in-nullpointerexception-fine – Frank van Puffelen Dec 02 '20 at 19:54

2 Answers2

0

snapshot.getValue(Double.class) returns a Double object, not a double primitive. You should check this object for null before unboxing it. It can be null when no data exists in the snapshot.

Double offset = snapshot.getValue(Double.class);
if (offset != null) {
    double o = offset;
}
else {
    // figure out what you want to do when the data is not there
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

There are a few options. You can write it in a try...catch

double offset;

try {
    offset = snapshot.getValue(Double.class);
}catch(Exception e){
    offset = 0; //Default value
}

Another option is to use a ternary operator

double offset = snapshot.getValue(Double.class) != null ? snapshot.getValue(Double.class) : 0;
Garren Fitzenreiter
  • 781
  • 1
  • 5
  • 22