如何在Firebase数据库中添加数据?

时间:2019-02-27 09:54:08

标签: java android firebase firebase-realtime-database

我想用android studio创建一个聊天应用项目,当我想将数据保存在Firebase数据库中时,我是新开发人员,我的应用崩溃了,这是我的代码:

public void register(final String username, final String email, final String password)
{
    auth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task)
                {
                    if (task.isSuccessful())
                    {
                        FirebaseUser firebaseUser = auth.getCurrentUser();
                        assert firebaseUser != null;
                        String userid = firebaseUser.getUid();

                        HashMap<String , String> hashMap = new HashMap<>();
                        hashMap.put("id", userid);
                        hashMap.put("username", username);
                        hashMap.put("imageURL", "defualt");
                        hashMap.put("password", password);

                        reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

                        reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task)
                            {
                                if (task.isSuccessful())
                                {
                                    Intent intent = new Intent(RegisterActivity.this,
                                            MainActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        });
                    }
                    else
                        Toast.makeText(RegisterActivity.this, "You can't register woth this email or password",
                                Toast.LENGTH_SHORT).show();
                }
            });
}

,当我要保存数据时,此任务等于false:

                                    if (task.isSuccessful())
                                {
                                    Intent intent = new Intent(RegisterActivity.this,
                                            MainActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                    finish();
                                }

1 个答案:

答案 0 :(得分:1)

确保您使用的是实时数据库而不是Cloud Firestore。可能是这样。