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);
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)
.
使用getValue(String.class)
代替getValue().toString();
您正在使用不必要的for循环。您已经知道什么是用户uid。删除for循环,然后重试。
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.