Skip to content Skip to sidebar Skip to footer

Retrieve Current User's Data (user_id) Firebase?

firebaseAuth = FirebaseAuth.getInstance(); mDatabase = FirebaseDatabase.getInstance(); mDb = mDatabase.getReference(); FirebaseUser user = firebase

Solution 1:

To solve this, please use the following code:

firebaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance();
mDb = mDatabase.getReference();
FirebaseUser user = firebaseAuth.getCurrentUser();
userKey = user.getUid();

mDb.child("Tunanetra").child(userKey).addValueEventListener(newValueEventListener() {
    @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
        String userID = dataSnapshot.child("user_id").getValue(String.class);
        Log.d(TAG, "Name: " + userID);
    }

    @OverridepublicvoidonCancelled(DatabaseError databaseError) {}
});

With this code, you'll be able to print out in the logcat, the id of the users that is authenticated and exists under Tunanetra node. If the user exists under the Orangtua node, then just change Tunanetra with Orangtua.

Solution 2:

I think instead of

mDb = mDatabase.getReference(); 

you should be using

mDb = mDatabase.getReference("Tunanetra");

because that's where the user you're looking for is nested at.

Solution 3:

It's simple. If you want to retrieve user data. Then you have to first select the child node in which you want to look for the user.

You have to Nodes Tunanetra and Orangtua

Else you can try this order by approach.

FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
        FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
        DatabaseReference mDb = mDatabase.getReference();
        FirebaseUser user = firebaseAuth.getCurrentUser();
        String userKey = user.getUid();

        //First Approach
        mDb.child("Tunanetra").child(userKey).addValueEventListener(newValueEventListener() {
            @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
                String userID = String.valueOf(dataSnapshot.child("user_id").getValue());
            }

            @OverridepublicvoidonCancelled(DatabaseError databaseError) {

            }
        });

        //Second Approach
        mDb.child("Tunanetra").orderByChild("email").equalTo(user.getEmail()).limitToFirst(1).addValueEventListener(newValueEventListener() {
            @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {

                if(dataSnapshot.getChildrenCount()>0){
                    for(DataSnapshot data : dataSnapshot.getChildren()){
                        String userID = String.valueOf(data.child("user_id").getValue());
                    }
                }
            }

            @OverridepublicvoidonCancelled(DatabaseError databaseError) {

            }
        });

Post a Comment for "Retrieve Current User's Data (user_id) Firebase?"