简体   繁体   English

无法使用 firebase 创建帐户?

[英]failed to create account with firebase?

i tried to do everything correctly and can't seem to find what's wrong here, i even created the project again from scratch but still it doesn't work, but i get the "failed" toast when trying to create an account, i added the internet permission too.我试图正确地做所有事情,但似乎无法找到这里出了什么问题,我什至从头开始重新创建了该项目,但仍然无法正常工作,但是我在尝试创建帐户时得到了“失败”的吐司,我补充说互联网许可也是如此。 i also don't get any error in logcat to show it here, how can this be solved ?我在 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);

}
}

i fixed, the problem was i had allow read, write: if false;我修复了,问题是我allow read, write: if false; in firestore and it needed to be allow read, write: if true;在 firestore 中,需要allow read, write: if true;

This could be solved by following good debugging practices.这可以通过遵循良好的调试实践来解决。

Meaningful error messages有意义的错误信息

When you encounter an error and wish to send a toast/alert to the user, send something meaningful to inform them what went wrong.当您遇到错误并希望向用户发送 Toast/alert 时,发送一些有意义的信息来通知他们出了什么问题。 As an example, instead of "failed" or "failed task", use "failed to upload user data" or "failed to create new user".例如,不要使用“failed”或“failed task”,而使用“failed to upload user data”或“failed to create new user”。

Each function will normally return a handful of exception classes that can be used to provide a better toast/alert message.每个函数通常会返回一些异常类,可用于提供更好的 toast/alert 消息。 Consulting the documentation for createUserWithEmailAndPassword(email, password) you can see what exceptions are thrown and use instanceof to determine the cause of the problem.查阅createUserWithEmailAndPassword(email, password)的文档createUserWithEmailAndPassword(email, password)您可以看到抛出了哪些异常并使用instanceof来确定问题的原因。 For example, if e instanceof FirebaseAuthInvalidCredentialsException was true , you could toast "failed to create new user: invalid email".例如,如果e instanceof FirebaseAuthInvalidCredentialsExceptiontrue ,您可以吐司“无法创建新用户:无效电子邮件”。

While this seems tedious, it will save head-scratching later when a user encounters a problem and sends you a bug report/email about it.虽然这看起来很乏味,但当用户遇到问题并向您发送有关它的错误报告/电子邮件时,它会避免以后头疼。 These steps will help you find any issues without needing access to logs for trivial problems such as incorrectly filled forms.这些步骤将帮助您发现任何问题,而无需访问日志以解决诸如错误填写表格之类的小问题。

Log exceptions记录异常

The reason you have no information on what went wrong is because you haven't made use of the exception provided in each onFailure handler ( public void onFailure(@NonNull Exception e) { ... } ).您没有关于发生了什么问题的信息的原因是因为您没有使用每个onFailure处理程序中提供的异常( public void onFailure(@NonNull Exception e) { ... } )。 These handlers provide you with the exception that caused the problem which you can save to the log using Log.e("yourActivityName:yourFunctionName", "short message", e) .这些处理程序为您提供了导致问题的异常,您可以使用Log.e("yourActivityName:yourFunctionName", "short message", e)将其保存到日志中。 You can also use e.getMessage() to get information about the thrown error.您还可以使用e.getMessage()获取有关抛出的错误的信息。

In an onComplete(Task<?> task) handler, if task.isSuccessful() returns false , you can find out why it is false by calling Exception e = task.getException() and then log it.onComplete(Task<?> task)处理程序中,如果task.isSuccessful()返回false ,您可以通过调用Exception e = task.getException()找出它为什么为 false ,然后记录它。

Fail-fast programming快速失败的编程

If you ever find that you have an if - else pair where the if section contains lots more code than the else section, it is likely to be a sign that you should flip the condition.如果你发现你有一个if - else对,其中if部分包含的代码比else部分多,这可能表明你应该翻转条件。

Whilst keeping your code cleaner by using less indentation, it also avoids having to scroll through a long if that probably contains more if and else statements.虽然通过使用较少的缩进保持你的代码更加清晰,同时也避免了通过长时间不必滚动if ,可能含有较多的ifelse报表。

For example,例如,

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
// ...

Example例子

As an example of applying these changes, I have made edits to the code you provided applying fail-fast techniques, simplifying error handling, logging exceptions, using OnSuccessListener and OnFailureListener instead of OnCompleteListener where appropriate,作为应用这些更改的示例,我对您提供的代码进行了编辑,应用快速失败技术,简化错误处理,记录异常,在适当的情况下使用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
            }
        });
}

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

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