Ad

When Querying The Database Has The Object But GetValue() Will Return Null

- 1 answer

I keep user per unique value into real time firebase as display at this link image:

get user according to email - database firebase

I want to get user by email, so I try to doing that like this:

 private void getUserFromRealtimeFirebase(String email) {
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    mDatabaseReference = mFirebaseDatabase.getReference().child("user");
    Query query = mDatabaseReference.orderByChild("email").equalTo(email);

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Log.i("TAG", "dataSnapshot value = " + dataSnapshot.getValue().toString());

            if (dataSnapshot.exists()) {
                Log.d("Tag", "user exists"); 
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

but I always get at callback listener: dataSnapshot: key = user , value = null even when email exists.

enter image description hereenter image description here

I wonder what is wrong?

Ad

Answer

EDIT:

If you don't want to pass userId, use this query:

mDatabaseReference = mFirebaseDatabase.getReference();
Query query = mDatabaseReference.orderByChild("user/email").equalTo(email);

You are missing the user-id level. You should change your code to:

private void getUserFromRealtimeFirebase(String email, String userId) {
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    mDatabaseReference = mFirebaseDatabase.getReference().chlid(userId).child("user");
    Query query = mDatabaseReference.orderByChild("email").equalTo(email);
...
...
}

Btw I would consider re-arranging the data structure to - newsapp -> users -> {userId} -> {name, image, firebase-token, email....}.

Also, on the callback - first check if dataSnapshot.exists() and only after that use getValue(), even if inside a log, to avoid null pointer exception.

Ad
source: stackoverflow.com
Ad