如何在用户注册期间将数据存储在 Firebase 的实时数据库中? [英] How to store data in realtime database in firebase during user registration?

查看:16
本文介绍了如何在用户注册期间将数据存储在 Firebase 的实时数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作具有用户个人资料的类似社交媒体的应用.我想在他们注册时使用他们的 uid 保存他们的个人资料数据.尽管注册成功,但配置文件并未保存在 firebase 数据库中.我还检查了规则,为经过身份验证的用户设置了读写.

I'm making socialmedia-like app that has user profile. I want to save their profile data upon their registration using their uid. Although the registration is successful, profile is not saving in the firebase database. I've also checked the rules, and read and write is set for authenticated users.

这是我的代码:

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

private Button btn_reg;
private EditText etName, etEmail, etPassword, etCPassword, etMobile, etSchoolCompany, etLocation;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    Firebase.setAndroidContext(this);

    firebaseAuth = FirebaseAuth.getInstance();

    progressDialog = new ProgressDialog(this);

    btn_reg = (Button)findViewById(R.id.btnRegister);
    etName = (EditText)findViewById(R.id.etName);
    etEmail = (EditText)findViewById(R.id.etEmail);
    etPassword = (EditText)findViewById(R.id.etPassword);
    etCPassword = (EditText)findViewById(R.id.etCPassword);
    etMobile = (EditText)findViewById(R.id.etMobile);
    etSchoolCompany = (EditText)findViewById(R.id.etSchoolCompany);
    etLocation = (EditText)findViewById(R.id.etLocation);

    btn_reg.setOnClickListener(this);
}

@Override
public void onClick (View view){
    if(view == btn_reg){
        registerUser();
    }
}

private void registerUser(){
    String name = etName.getText().toString();
    String mobile = etMobile.getText().toString();
    String SchoolCompany = etSchoolCompany.getText().toString();
    String location = etLocation.getText().toString();
    final String email = etEmail.getText().toString().trim();
    final String password = etPassword.getText().toString().trim();
    String cpassword = etCPassword.getText().toString().trim();

    progressDialog.setMessage("Registering..");
    progressDialog.show();

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

                        //THIS IS FOR STORING AUTHENTICATED USER'S DATA
                        final Firebase ref = new Firebase("https://myfirebase.firebaseio.com");
                        ref.authWithPassword(email, password, new Firebase.AuthResultHandler(){
                            @Override
                            public void onAuthenticated(AuthData authData){
                                // Authentication just completed successfully :)
                                Map<String, String> map = new HashMap<String, String>();
                                map.put("provider", authData.getProvider());
                                if(authData.getProviderData().containsKey("displayName")) {
                                    map.put("displayName", authData.getProviderData().get("displayName").toString());
                                }
                                ref.child("users").child(authData.getUid()).setValue(map);
                            }
                            @Override
                            public void onAuthenticationError(FirebaseError error) {
                //ERRORS TODO
                            }
                        });
                        progressDialog.hide();
                        Toast.makeText(RegisterActivity.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(RegisterActivity.this, "Registration failed, please try again", Toast.LENGTH_SHORT).show();
                    }
                }

            });
}


}

推荐答案

来自 createUserWithEmailAndPassword 方法参考

尝试使用给定的电子邮件地址和密码创建新的用户帐户.如果成功,它还会让用户登录应用.

Tries to create a new user account with the given email address and password. If successful, it also signs the user in into the app.

这意味着您无需在注册过程完成后再次对用户进行身份验证.

That means you don't need to authenticate the user again after the signup process completed.

为了确保任务完成并且 firebaseUser 不为空,最好将 AuthStateListener 添加到您的 FirebaseAuth 而不是将数据保存在里面onComplete 方法,代码在官方指南

To make sure that the task is complete and the firebaseUser is not null, better add AuthStateListener to your FirebaseAuth instead of saving data inside onComplete method, the code is in the official guide

然后您可以在用户通过身份验证后保存数据.

Then you can save the data if the user is authenticated.

public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
    FirebaseUser user = firebaseAuth.getCurrentUser();
    if (user != null) {
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        Map<String, String> map = new HashMap<>();
        map.put("provider", user.getProviders().get(0));
        if(user.getProviderData().containsKey("displayName")) {
            map.put("displayName", user.getProviderData().get("displayName").toString());
        }
        ref.child("users").child(user.getUid()).setValue(map);
    } 
}

这篇关于如何在用户注册期间将数据存储在 Firebase 的实时数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆