当前位置: 首页 > 知识库问答 >
问题:

如何在Android环境下检索Firebase实时数据库中认证用户的用户数据

梁浩
2023-03-14

我正试图从Firebase实时数据库中检索当前登录用户的配置文件数据。我已经通过电子邮件和密码验证了我的用户。然后,我将注册数据保存在数据库中,作为一个对象,如下所示:(所有这些代码都在SignUpActivity中的onCreate中)。我将数据保存为用户对象。我的用户模型类有getter和setter,参数化和空白构造函数。

´´´´// Initialize FirebaseAuth and DatabaseReference
mFirebaseAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");

mFirebaseAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {

                    //save all data to database

                   String mUserId = mFirebaseAuth.getCurrentUser().getUid();

                        User user = new User(email, name,tel, address1,address2,user_type, mUserId);

                        //add to database
                        mDatabaseRef.child(mUserId).setValue(user);
//open main activity
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

因此,mUserId是经过身份验证的用户的用户ID。我的数据库结构如下,规则是默认公共的。

wish-store-42facaddclose
    users
        2GbVFSMFrihqVJ8OAXBa56owNW93
            address1: "juja"
            address2:  "Town"
            email:  "a.bea@gmail.com"
            phone:  "+237638256239"
            userId:  "2GbVFSMFrihqVJ8OAXBa56owNW93"
            userName:  "Beatrice Njambi"
            userType:  "Buyer Account"
//instantiate firebaseAuth
mFirebaseAuth = FirebaseAuth.getInstance();
userName = (TextView) findViewById(R.id.userNameHeader);

//check to see if user is logged in
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if (mFirebaseUser == null) {
    //the user is not logged in, start login activity
    loadLogInView();
} else {


    String mUserId = mFirebaseUser.getUid();

    root = FirebaseDatabase.getInstance().getReference();

    DatabaseReference mDatabaseRef = root.child("users").child(mUserId);

    ValueEventListener profileListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            User user = dataSnapshot.getValue(User.class);
            userName.setText(user.getUserName());
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.i("Read failed", databaseError.getMessage());
        }
    };
    mDatabaseRef.addValueEventListener(profileListener);


}

提前谢了。

共有1个答案

赵献
2023-03-14

尝试直接为数据库对象添加ValueEventListener,而不是稍后设置。尝试检查是否已初始化FirebaseAuth

 类似资料: