Android Firebase 实时数据库替换数据而不是添加新数据

Pfi*_*ntz 2 android firebase-authentication firebase-realtime-database

我正在尝试将数据插入 Firebase 实时数据库。我的应用程序的逻辑是在用户注册时在数据库的用户列下创建一个包含用户名和密码的新字段。

该应用程序在注册时需要电子邮件、用户名和密码。我正在使用 Firebase Auth 来做到这一点。当我运行应用程序时,我可以成功注册并在数据库中插入值,但是每当新用户注册而不是创建新用户时,数据库中的值就会被替换。请帮助,如果我做错了什么。这是我的代码。

firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        UserInformation userInformation = new UserInformation(username,password);
                        //checking if success
                        if(task.isSuccessful()){

                            databaseReference.child("users").setValue(userInformation);
                            Toast.makeText(MainActivity.this,"Successfully registered",Toast.LENGTH_LONG).show();
                            finish();
                            startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
                        }else{
                            //display some message here
                            Toast.makeText(MainActivity.this,"Registration Error",Toast.LENGTH_LONG).show();
                        }
                        progressDialog.dismiss();
                    }
                });
Run Code Online (Sandbox Code Playgroud)

小智 5

databaseReference.child("users").setValue(userInformation)
Run Code Online (Sandbox Code Playgroud)

这将替换现有数据。如果要将值添加为新子项,则需要使用push(),这将生成唯一 id,然后插入新数据。试试下面的代码。

databaseReference.child("users").push().setValue(userInformation)
Run Code Online (Sandbox Code Playgroud)

  • 当我们谈论用户时,我建议将它们存储在他们的 UID 下而不是推送 ID:`databaseReference.child("users").child(task.getUser().getUid()).setValue(userInformation) `. 这使得以后查找用户信息变得容易,并确保每个用户只存储一次(因为下次登录同一个用户会给他们相同的 UID)。 (3认同)