How to link between Authenticated users and Database in Firebase?

后端 未结 1 690
忘掉有多难
忘掉有多难 2020-12-28 18:19

I have Firebase Authentication in my Android app. My question is how do I link between authenticated users (that appear in Firebase::Auth tab in the Firebase co

相关标签:
1条回答
  • 2020-12-28 18:38

    After authentication, create a child with the UID given by Firebase, and set its value to your user class:

    //get firebase user
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    
    //get reference
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(USERS_TABLE);
    
    //build child
    ref.child(user.getUid()).setValue(user_class);
    

    USERS_TABLE is a direct child of root.

    Then when you want to retrieve the data, get a reference to the user by its UID, listen for addListenerForSingleValueEvent() (invoked only once), and iterate over the result with reflection:

    //get firebase user
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    
    //get reference
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(USERS_TABLE).child(user.getUid());
    //IMPORTANT: .getReference(user.getUid()) will not work although user.getUid() is unique. You need a full path!
    
    //grab info
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            final Profile tempProfile = new Profile(); //this is my user_class Class
            final Field[] fields = tempProfile.getClass().getDeclaredFields();
            for(Field field : fields){
                Log.i(TAG, field.getName() + ": " + dataSnapshot.child(field.getName()).getValue());
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    

    edit:

    Or without reflection:

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        final Profile p = dataSnapshot.getValue(Profile.class);
    }
    
    0 讨论(0)
提交回复
热议问题