Reputation: 35
I get java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
when my code reaches the valueEventListener although while debugging, it seems to me that the child value is not null.
Here is the image of the code:
This is how the database looks like:
Solved the problem by completely deleting the code and starting again. This time I checked with firebase github and I did it like this(mostly the same thing? i wish i knew what was wrong with my first code):
userReference = FirebaseDatabase.getInstance().getReference().child("users").child(uid);
ValueEventListener userListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//Get user object
currentUser = dataSnapshot.getValue(User.class);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// [START_EXCLUDE]
Toast.makeText(UserAreaActivity.this, "Failed to load post.",
Toast.LENGTH_SHORT).show();
}
};
userReference.addValueEventListener(userListener);
Upvotes: 0
Views: 86
Reputation: 138824
Simply use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String country = dataSnapshot.child("country").getValue(String.class);
String city = dataSnapshot.child("city").getValue(String.class);
Log.d(TAG, country + " / " + city);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be the exact country
and city
of your user.
Upvotes: 0
Reputation: 605
You are using unnecessary for loop.You already know what user uid is.Remove for loop then try again.
Upvotes: 0
Reputation: 846
The only place, in the code shown, where you could get a NPE with that message is in the call:
...child("users").child(uid);
So I'd check that uid variable, work out a way to deal with such scenario (uid == null)
.
Upvotes: 1