且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Firebase 中在经过身份验证的用户和数据库之间建立链接?

更新时间:2023-12-05 22:45:10

认证后,使用 Firebase 提供的 UID 创建一个 child,并将其值设置为您的用户类:

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 是 root 的直接子级.

USERS_TABLE is a direct child of root.

然后当你想要检索数据时,通过其 UID 获取对用户的引用,监听 addListenerForSingleValueEvent()(仅调用一次),并通过反射迭代结果:>

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) {
    }
});

或者没有反射:

@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    final Profile p = dataSnapshot.getValue(Profile.class);
}