繁体   English   中英

在Firebase中创建用户时如何获取用户ID

[英]How can I get user id at the time of user creation in Firebase

在我的项目中,只有管理员可以将用户添加到Firebase。 在创建时,我想获取用户ID,因为我想在Firebase数据库中设置该用户的配置文件。

public void addNewFaculty(View view){
    String name,email,password,rePassword;
    name = txtname.getText().toString();
    email = txtEmail.getText().toString().trim();
    password = txtPassword.getText().toString().trim();
    rePassword = txtRepassword.getText().toString().trim();
    if(password.equals(rePassword))
    {
        Toast.makeText(this, "Password is not match", Toast.LENGTH_SHORT).show();
        return;
    }
    databaseReference= FirebaseDatabase.getInstance().getReference();
    firebaseUser = firebaseAuth.getCurrentUser();
    String id= firebaseUser.getUid();
    databaseReference = databaseReference.child("Profile").child(id);
    databaseReference.child("Name").setValue(name);
    // and some other things
    firebaseAuth.createUserWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(task.isSuccessful()){
                        Toast.makeText(getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(), "Please try Again", Toast.LENGTH_SHORT).show();
                    }
                }
            });

}

我的firebase结构是,而我的firebase结构如下。 我想在创建用户时获取用户ID, 这是我的Firebase身份验证图像

并想在这里设置ID

当您在firebase auth中创建用户时,它会自动登录。因此,如果方法如下,则可以在onComplete()中获取ID:

    if(task.isSuccessful()){
       String id1 = firebaseAuth.getCurrentUser().getUid();
       //For adding into database

       databaseReference = databaseReference.child("Profile").child(id1);
       databaseReference.child("Name").setValue(name);

       Toast.makeText(getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_SHORT).show();
    }else{
       Toast.makeText(getApplicationContext(), "Please try Again", Toast.LENGTH_SHORT).show();
    }

@Himashu Nain对这个问题的回答不正确。 firebaseAuth.getCurrentUser().getUid(); 由于管理员已登录并且是当前用户,因此将获取管理员的userId。 @AtifRizwan希望创建员工帐户的userId(而不是管理员的!)。 要获取所创建帐户的用户ID,您可以从完成侦听器返回的任务中获取用户信息:即

 mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());

                if (task.isSuccessful()) {
                    FirebaseUser user = task.getResult().getUser();

                    Log.d(TAG, "onComplete: uid=" + user.getUid());
                }
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM