如何在实时数据库中将用户 ID 设置为与身份验证中的用户 ID 相同? [复制]

Posted

技术标签:

【中文标题】如何在实时数据库中将用户 ID 设置为与身份验证中的用户 ID 相同? [复制]【英文标题】:how to set user ID in Realtime database the same in user ID in Authentication? [duplicate] 【发布时间】:2021-09-27 18:48:16 【问题描述】:

你能帮我解决我的问题吗?当用户在我的应用程序中成功注册时,我想将实时数据库中的 ID 设置为与身份验证中的用户 ID 相同。我将使用用户 ID 从我的应用程序中检索用户的数据。就像用户将从个人资料活动中看到他的数据一样。请问怎么做?

这是我的注册活动中的代码

package com.example.biowit;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class Bio_SignUp extends AppCompatActivity 


EditText txtbx_SU_FullName, txtbx_SU_CPNum, txtbx_SU_Email, txtbx_SU_Pass, txtbx_SU_ConfirmPass; // edit text declarations
Button btn_Register; // button/s declaration/s
ImageButton btn_SU_Back;
FirebaseAuth FbaseAuth_SU; //for authentication
FirebaseDatabase rootNode; // for realtime database
DatabaseReference reference;


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE); // hides the title bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getSupportActionBar().hide(); // hides the action bar

    setContentView(R.layout.activity_bio_sign_up);

    txtbx_SU_FullName = findViewById(R.id.txtbx_SU_FullName);
    txtbx_SU_Email = findViewById(R.id.txtbx_SU_Email);
    txtbx_SU_CPNum = findViewById(R.id.txtbx_SU_CPNum);
    txtbx_SU_Pass = findViewById(R.id.txtbx_SU_Pass);
    txtbx_SU_ConfirmPass = findViewById(R.id.txtbx_SU_ConfirmPass);
    btn_Register = findViewById(R.id.btn_Register);
    btn_SU_Back = findViewById(R.id.btn_SU_Back);

    FbaseAuth_SU = FirebaseAuth.getInstance();
    rootNode = FirebaseDatabase.getInstance("https://biowit-log-in-default-rtdb.asia-southeast1.firebasedatabase.app/");
    reference = rootNode.getReference("users");

    btn_Register.setOnClickListener(new View.OnClickListener() 

        @Override
        public void onClick(View v) 


            String fullname = txtbx_SU_FullName.getText().toString();
            String email = txtbx_SU_Email.getText().toString();
            String cpnum = txtbx_SU_CPNum.getText().toString();
            String password = txtbx_SU_Pass.getText().toString();
            String ConPassword = txtbx_SU_ConfirmPass.getText().toString();
            String UserID = FbaseAuth_SU.getUid();
            UserHelper UHelper = new UserHelper(fullname, cpnum, email, password);

            if(fullname.isEmpty()) // condition if full name field is empty,
                txtbx_SU_FullName.setError("This field cannot be empty."); // this error message will be shown.
                return;
            

            if(cpnum.isEmpty()) // condition if full name field is empty,
                txtbx_SU_CPNum.setError("This field cannot be empty."); // this error message will be shown.
                return;
            

            if(email.isEmpty()) // condition if full name field is empty,
                txtbx_SU_Email.setError("This field cannot be empty."); // this error message will be shown.
                return;
            

            if(password.isEmpty()) // condition if full name field is empty,
                txtbx_SU_Pass.setError("This field cannot be empty."); // this error message will be shown.
                return;
            

            if(ConPassword.isEmpty()) // condition if full name field is empty,
                txtbx_SU_ConfirmPass.setError("This field cannot be empty."); // this error message will be shown.
                return;
            

            if (!ConPassword.equals(password)) // condition if the confirm password is not equals to password,
                txtbx_SU_ConfirmPass.setError("Password does not match."); // this error message will be shown.
                return;
            

            // notification that says the data is validated.
            Toast.makeText(Bio_SignUp.this, "Data Validated", Toast.LENGTH_LONG).show();

            //Email address and password authentication in the database.
            FbaseAuth_SU.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() 

                @Override
                public void onSuccess(AuthResult authResult)  // send the user to the log - in screen.

                    reference.child(UserID).setValue(UHelper).addOnSuccessListener(new OnSuccessListener<Void>() 

                        @Override
                        public void onSuccess(Void unused)  // notification that the user was successfully registered.
                            Toast.makeText(Bio_SignUp.this, "Sign - up Successfully!", Toast.LENGTH_LONG).show();
                        

                    ).addOnFailureListener(new OnFailureListener() 
                        @Override
                        public void onFailure(@NonNull Exception e)   // when user failed to sign up, an error message shows.
                            Toast.makeText(Bio_SignUp.this, e.getMessage(), Toast.LENGTH_LONG).show();

                        
                    );

                    startActivity(new Intent(Bio_SignUp.this, Bio_LogIn.class));
                

            ).addOnFailureListener(new OnFailureListener() 
                @Override
                public void onFailure(@NonNull Exception e)  // an error when email and pass is wrong or invalid.
                    Toast.makeText(Bio_SignUp.this, e.getMessage(), Toast.LENGTH_LONG).show();
                
            );
        
    );

    btn_SU_Back.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            finish();
        
    );

【问题讨论】:

【参考方案1】:

如果您在没有用户登录的情况下使用String UserID = FbaseAuth_SU.getUid();,那么它可能会返回 null。而是在用户使用getUsergetUid 方法登录后获取用户的UID:

@Override
public void onSuccess(AuthResult authResult) 
  String userUID = authResult.getUser().getUid()
  Toast.makeText(Bio_SignUp.this, userUID.getUid(), Toast.LENGTH_LONG).show();
 
  //Now add data to Realtime Database
  reference.child(userUID).setValue(UHelper) 

【讨论】:

所以当前登录的用户必须登录才能从真实数据库中设置其 id 与 auth 用户 ID 相同? @ThredgePaul 如果您想要当前登录用户的 UID(或任何数据),那么是的,他们必须登录。【参考方案2】:

好的,因此您可以随时根据需要格式化数据库,但下面的代码将在名为“users”的子项下设置用户的全名、电子邮件、密码和号码,并且在该子项中,“users”将是另一个具有userId 为 key 在创建用户后设置此代码,您可以在 setValue 之后设置一个 onSuccessListener 来做你想做的事:

UserID = FirebaseAuth.getInstance().getCurrentUser().getUid()

Map<String, Object> map = new HashMap<>();
map.put("full_name", fullname);
map.put("email", email);
map.put("password", password);
map.put("number", cpnum);

reference.child("users").child(UserID).setValue(map);

【讨论】:

以上是关于如何在实时数据库中将用户 ID 设置为与身份验证中的用户 ID 相同? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

为啥注册用户后 Firebase 实时数据库用户 ID 与 Firebase 身份验证 UID 不匹配?

如何在 ASP.NET Core 中将角色添加到 Windows 身份验证

如何将 Firebase 身份验证链接到实时数据库?

如何保护Redis&Socket.IO实时服务器,以便只有经过身份验证的用户才能收听?

多个用户的 Firebase 实时数据库身份验证

Flutter Firebase signInWithCustomToken 与现有身份验证系统的用户 ID?