【问题标题】:failed to create account with firebase?无法使用 Firebase 创建帐户?
【发布时间】:2020-03-20 07:29:38
【问题描述】:

我尝试正确地做所有事情,但似乎找不到这里有什么问题,我什至从头开始重新创建项目,但仍然无法正常工作,但在尝试创建帐户时我得到了“失败”的祝酒词,我也添加了互联网权限。我在 logcat 中也没有任何错误显示在这里,如何解决?

public class CreateAccountActivity extends AppCompatActivity {

private Button btnCreateAcc;

private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser currentUser;

// firestore
private FirebaseFirestore database = FirebaseFirestore.getInstance();

private CollectionReference collectionReference = database.collection("Users");

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

    firebaseAuth = FirebaseAuth.getInstance();
    authStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            currentUser = firebaseAuth.getCurrentUser();

            if (currentUser != null) {

            } else {

            }
        }
    };

    btnCreateAcc = findViewById(R.id.create_acct_button);

    btnCreateAcc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!TextUtils.isEmpty(etEmail.getText().toString()) &&
                    !TextUtils.isEmpty(etPassword.getText().toString()) &&
                    !TextUtils.isEmpty(etUserName.getText().toString())) {

                String email = etEmail.getText().toString();
                String password = etPassword.getText().toString();
                String username = etUserName.getText().toString();

                createUserEmailAccount(email, password, username);
            } else {
                Toast.makeText(CreateAccountActivity.this, "Please fill in all fields"
                        , Toast.LENGTH_SHORT).show();
            }

        }
    });
}

private void createUserEmailAccount(String email, String password, final String username) {
    if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) &&
            !TextUtils.isEmpty(username)) {

        progressBar.setVisibility(View.VISIBLE);

        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            currentUser = firebaseAuth.getCurrentUser();

                            assert currentUser != null;
                            final String currentUserId = currentUser.getUid();

                            Map<String, String> userObj = new HashMap<>();
                            userObj.put("userId", currentUserId);
                            userObj.put("username", username);

                            collectionReference.add(userObj)
                                    .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                                        @Override
                                        public void onSuccess(DocumentReference documentReference) {
                                            documentReference.get()
                                                    .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                                        @Override
                                                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                                            if (Objects.requireNonNull(task.getResult()).exists()) {
                                                                progressBar.setVisibility(View.INVISIBLE);

                                                                String name = task.getResult()
                                                                        .getString("username");

                                                                Intent intent = new Intent(CreateAccountActivity.this,
                                                                        PostJournalActivity.class);
                                                                intent.putExtra("username", name);
                                                                intent.putExtra("userId", currentUserId);
                                                                startActivity(intent);
                                                            } else {
                                                                progressBar.setVisibility(View.INVISIBLE);
                                                            }
                                                        }
                                                    });
                                        }
                                    })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Toast.makeText(CreateAccountActivity.this, "failed"
                                                    , Toast.LENGTH_SHORT).show();
                                        }
                                    });
                        } else {
                            Toast.makeText(CreateAccountActivity.this, "failed task"
                                    , Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(CreateAccountActivity.this, "failed on complete"
                                , Toast.LENGTH_SHORT).show();
                    }
                });

    } else {
        Toast.makeText(this, "failed else", Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onStart() {
    super.onStart();

    currentUser = firebaseAuth.getCurrentUser();
    firebaseAuth.addAuthStateListener(authStateListener);

}
}

【问题讨论】:

  • 你的 logcat 输出是什么?
  • 也许您在存储功能中遇到了“失败”的祝酒词。创建帐户后立即添加日志或 toast。
  • 您是否在 Firebase 中启用了来自身份验证的电子邮件提供程序?
  • 另外,您是否启用了 Firestore?
  • @NovoLucas 是的,我做到了。

标签: android firebase google-cloud-firestore firebase-authentication


【解决方案1】:

我修好了,问题是我在 Firestore 中有 allow read, write: if false; 它必须是allow read, write: if true;

【讨论】:

  • 将您的答案标记为已接受并关闭问题
【解决方案2】:

这可以通过遵循良好的调试实践来解决。

有意义的错误信息

当您遇到错误并希望向用户发送祝酒/警报时,请发送有意义的内容以通知他们发生了什么错误。例如,不要使用“失败”或“失败的任务”,而是使用“上传用户数据失败”或“创建新用户失败”。

每个函数通常会返回一些异常类,这些异常类可用于提供更好的 toast/alert 消息。查阅createUserWithEmailAndPassword(email, password) 的文档,您可以查看引发了哪些异常并使用instanceof 确定问题的原因。例如,如果e instanceof FirebaseAuthInvalidCredentialsExceptiontrue,您可以举杯“创建新用户失败:无效电子邮件”。

虽然这看起来很乏味,但当用户遇到问题并向您发送有关该问题的错误报告/电子邮件时,它会节省您的时间。这些步骤将帮助您找到任何问题,而无需访问日志以解决诸如表格填写错误等琐碎问题。

记录异常

您不知道发生了什么问题的原因是因为您没有利用每个onFailure 处理程序(public void onFailure(@NonNull Exception e) { ... }) 中提供的异常。这些处理程序为您提供导致问题的异常,您可以使用Log.e("yourActivityName:yourFunctionName", "short message", e) 将其保存到日志中。您还可以使用e.getMessage() 获取有关抛出错误的信息。

onComplete(Task&lt;?&gt; task) 处理程序中,如果task.isSuccessful() 返回false,您可以通过调用Exception e = task.getException() 找出它为假的原因,然后记录它。

快速失败编程

如果您发现您有一个if-else 对,其中if 部分包含比else 部分更多的代码,则很可能表明您应该翻转条件。

在通过使用更少的缩进来保持代码更简洁的同时,它还避免了滚动可能包含更多 ifelse 语句的长 if

例如,

if (!requiredVariable1.isEmpty() && !requiredVariable2.isEmpty()) {
    // ...
    // many (nested) lines of code
    // ...
} else {
    Log.e(TAG, "a required variable was empty");
}
if (requiredVariable1.isEmpty() || requiredVariable2.isEmpty()) {
    Log.e(TAG, "a required variable was empty");
    return;
}

// ...
// many lines of code
// ...

示例

作为应用这些更改的示例,我对您提供的代码进行了编辑,应用了快速失败技术、简化错误处理、记录异常,在适当的情况下使用 OnSuccessListenerOnFailureListener 而不是 OnCompleteListener

private void createUserEmailAccount(String email, String password, final String username) {
    if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
        Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show();
        return;
    }

    progressBar.setVisibility(View.VISIBLE);

    firebaseAuth.createUserWithEmailAndPassword(email, password)
        .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
            @Override
            public void onSuccess(@NonNull Task<AuthResult> task) {
                currentUser = firebaseAuth.getCurrentUser();

                assert currentUser != null;
                final String currentUserId = currentUser.getUid();

                Map<String, String> userObj = new HashMap<>();
                userObj.put("userId", currentUserId);
                userObj.put("username", username); // unknown source for variable: username

                collectionReference.add(userObj)
                    .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                        @Override
                        public void onSuccess(DocumentReference documentReference) {
                            documentReference.get() // why redownload from database? you could just use values of "userObj"
                                .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                    @Override
                                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                        progressBar.setVisibility(View.INVISIBLE);

                                        if (!task.isSuccessful()
                                          || !Objects.requireNonNull(task.getResult()).exists()) {
                                            // show a error message?
                                            return;
                                        }

                                        String name = task.getResult()
                                                .getString("username");

                                        Intent intent = new Intent(CreateAccountActivity.this,
                                                PostJournalActivity.class);
                                        intent.putExtra("username", name);
                                        intent.putExtra("userId", currentUserId);
                                        startActivity(intent);
                                    }
                                });
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(CreateAccountActivity.this, "failed to add user data"
                                    , Toast.LENGTH_SHORT).show();
                            Log.e("CreateAccountActivity", "failed to add user data", e); // log error to logcat
                        }
                    });

            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(CreateAccountActivity.this, "failed to create user"
                        , Toast.LENGTH_SHORT).show();
                Log.e("CreateAccountActivity", "failed to create user", e); // log error to logcat
            }
        });
}

【讨论】:

  • 谢谢,这很棒,会记住它以备将来编码和提问。
猜你喜欢
  • 2020-10-15
  • 2018-08-14
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
相关资源
最近更新 更多