空对象引用上的“android.content.Intent com.google.android.gms.auth.api.signin.GoogleSignInClient.getSignInIntent()”

ton*_*ony 1 android google-api android-intent google-signin

我正在尝试在我的应用程序中实现 Google 登录,但我不断收到此错误'android.content.Intent com.google.android.gms.auth.api.signin.GoogleSignInClient.getSignInIntent()' on a null object reference

我在这里遵循了来自 firebase 网站的教程 --> https://firebase.google.com/docs/auth/android/google-signin

这是我的代码

private void googleSignIn() {

    Intent intent = googleSignInClient.getSignInIntent();
    startActivityForResult(intent, RC_SIGN_IN);
}

@Override
public 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(Objects.requireNonNull(account));
        } catch (ApiException e) {
            Log.w("hhm", "Google signin failed", e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

你有没有初始化googleSignInClient对象?

看起来你googleSignInClientnull,需要初始化:

1-在您的登录活动的 onCreate 方法中,配置 Google Sign-In 以请求您的应用所需的用户数据...

2-然后,同样在您的登录活动的 onCreate 方法中,使用您指定的选项创建一个 GoogleSignInClient 对象。

// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail()
        .build();

// Build a GoogleSignInClient with the options specified by gso.
googleSignInClient = GoogleSignIn.getClient(this, gso);
Run Code Online (Sandbox Code Playgroud)

参考