No 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) {
}
});
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 = ???
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With