将Android Studio连接到Firebase以进行身份​​验证

时间:2018-03-12 21:44:43

标签: java android firebase authentication firebase-authentication

我似乎无法通过以下代码与注册人员连接到firebase身份验证。我按照Android Studio帮助中的说明进行了firebase身份验证。我也在Gradle中添加了这一行: 编译com.google.firebase:firebase-auth:10.0.1'

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

    mAuth = FirebaseAuth.getInstance();
    username = (EditText) (findViewById(R.id.username));
    password = (EditText) (findViewById(R.id.password));
    signIn = (Button) (findViewById(R.id.signIn));
    register = (Button) (findViewById(R.id.register));
}

private void registerUser()
{
    loginUsernameString = username.getText().toString();
    loginPasswordString = password.getText().toString();

    mAuth.createUserWithEmailAndPassword(loginUsernameString, loginPasswordString)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Toast.makeText(LoginActivity.this, "Failed",
                                Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });
}
public void onClick(View view)
{
    if (view == signIn)
        registerUser();
}

1 个答案:

答案 0 :(得分:0)

尝试让用户使用mAuth,如果mAuth返回null,则验证用户身份时出现问题

mAuth.signInWithEmailAndPassword(loginUsernameString, loginPasswordString)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "signInWithEmail:success");
                    FirebaseUser user = mAuth.getCurrentUser().getUid();
                    Log.d(userCreated, ""+user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

                // ...
            }
        });

确保tu在你的gradle中有最新的编译,这就是

compile 'com.google.firebase:firebase-auth:11.2.0'

确保在firebase console中启用了对用户进行身份验证的选项

enter image description here

希望有所帮助

快乐的编码!