无法在Android中使用Firebase Google Auth登录

时间:2019-04-21 08:01:35

标签: android firebase firebase-authentication

我正在尝试在Android中集成由firebase auth提供的google登录。我所做的一切与firebase文档中给出的相同。当用户选择要登录应用的帐户停止并在下面给出的log cat窗口中显示错误时。

Caused by: java.lang.NullPointerException: Attempt to invoke virtual 
method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.signInWithCredential(com.google.firebase.auth.AuthCredential)' on a null object reference
    at com.app.bookbudi.Login.firebaseAuthWithGoogle(Login.java:99)
    at com.app.bookbudi.Login.onActivityResult(Login.java:86)

这是我的代码:

Login.java

public class Login extends AppCompatActivity {

SignInButton signIn;
GoogleSignInClient mGoogleSignInClient;
private static final int RC_SIGN_IN = 1;

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

signIn = findViewById(R.id.signIn);

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).
            requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();

mGoogleSignInClient = GoogleSignIn.getClient(this,gso);

signIn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent signInIntent = mGoogleSignInClient.getSignInIntent();
            startActivityForResult(signInIntent, RC_SIGN_IN);
        }
    });

 }

 @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == RC_SIGN_IN){

        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);

        try{
        GoogleSignInAccount account = task.getResult(ApiException.class);
        firebaseAuthWithGoogle(account);

    }catch(ApiException e){

            Toast.makeText(getApplicationContext(),"Login failed",TastyToast.LENGTH_SHORT).show();
        }
    }
  }

 private void firebaseAuthWithGoogle(GoogleSignInAccount acct){

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);

    fAuth.signInWithCredential(credential).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {

        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {

            if(task.isSuccessful()){

                Intent i = new Intent(Login.this,MainActivity.class);
                startActivity(i);
                finish();
            }
            else{

                Toast.makeText(getApplicationContext(),"Unable to login with google.",TastyToast.LENGTH_SHORT).show();

            }
        }
    });


  }

}

请让我知道我在上面的代码中做错了什么。

谢谢

1 个答案:

答案 0 :(得分:1)

您没有初始化Firebase身份验证。

SignInButton signIn;
GoogleSignInClient mGoogleSignInClient;
private static final int RC_SIGN_IN = 1;
//Add Firebase Auth
private FirebaseAuth fAuth;

在此onCreate

fAuth = FirebaseAuth.getInstance();