uana13
uana13

Reputation: 35

Getting null error although firebase reference is ok -

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:

code image

This is how the database looks like:

database image

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

Answers (4)

Alex Mamo
Alex Mamo

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

uzaysan
uzaysan

Reputation: 605

You are using unnecessary for loop.You already know what user uid is.Remove for loop then try again.

Upvotes: 0

rishikesh_07
rishikesh_07

Reputation: 1039

Use getValue(String.class) instead of getValue().toString();

Upvotes: 0

Perdi Estaquel
Perdi Estaquel

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

Related Questions