Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Unboxing may produce nullPointer Exception with firebase?

enter image description hereNo matter which user I am logged in as the "points" variable is always returned as 0. The same code works on separate activities and I cannot see what is different. When I hover over the datasnapshot is says that is may produce null pointer exception but it also says this on the other activities that work. I have spent ages trying out figure this out. Thanks.

        databaseUsers =FirebaseDatabase.getInstance().getReference("Users");
        final FirebaseAuth firebaseAuth;
        firebaseAuth = FirebaseAuth.getInstance();
        user = firebaseAuth.getCurrentUser();
        databaseUsers.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            points = dataSnapshot.child(user.getUid()).child("points").getValue(int.class);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    //Getting Total Points from Firebase Database
    databaseUsers.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            totalpoints = dataSnapshot.child(user.getUid()).child("totalpoints").getValue(int.class);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
like image 988
Christian Webb Avatar asked Mar 18 '18 19:03

Christian Webb


1 Answers

I assume that this is the line you're talking about, and that points is of some primitive type, such as int or long:

points = dataSnapshot.child(user.getUid()).child("points").getValue(int.class);

The problem here is that .getValue(Class<T>) returns a boxed type, for example Integer which may be null, when the data point doesn't exist. If you try to assign the returned value to a primitive type, the value needs to be unboxed, and unboxing a null value results in a null pointer exception.

To protect in case of null values, you need to add a null-check:

Integer value = dataSnapshot.child(user.getUid()).child("points").getValue(int.class);
if (value != null) {
    points = value;
} else {
    // TODO
    // points = ???
}
like image 115
janos Avatar answered Oct 19 '22 05:10

janos