android - Google 登录按钮导致空对象引用

标签 android

我正在尝试实现 Google 登录按钮,但在调用 signInButton.setSize() 时出现空对象引用错误。我使用 findViewById() 初始化按钮。我在 promptSignIn() 中执行此操作,它比 onCreate() 高几个堆栈级别。我尝试按照其他答案的建议在 onCreate() 中进行初始化,但我遇到了同样的错误。

YourOrdersActivity.java

package com.example.mattf.yankeetoyboxv1;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.tasks.Task;

/**
 * Created by mattf on 12/8/2017.
 */

public class SignInActivity extends BaseActivity{

    private GoogleSignInClient mGoogleSignInClient;
    private SignInButton signInButton;
    private static int RC_SIGN_IN=100;
    private static final String TAG="SignInActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isUserSignedIn();
    }

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

        isUserSignedIn();
    }

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

        //Result return from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed
            // no need to attach a listener
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void isUserSignedIn() {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

        if (account==null){
            promptSignIn();
        }
        else updateUI(account);
    }

    private void promptSignIn() {
        // 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
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        // Set the dimensions of the sign-in button
        signInButton = findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_STANDARD);
        signInButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                signIn();
            }
        });
    }

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent,RC_SIGN_IN);
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult();

            // Signed in successfully, show authenticated UI
            updateUI(account);

        } catch (Exception e) {
            Log.w(TAG, "signInResult:failed code=" + e.getMessage());
        }
    }

    protected void updateUI(GoogleSignInAccount account) {
        if (signInButton != null) signInButton.setVisibility(View.GONE);
    }
}

按钮位于链接到 YourOrdersActivity.java Activity 的 XML 文件中。

your_orders_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mattf.yankeetoyboxv1.YourOrdersActivity">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

LogCat

12-08 20:31:51.624 12373-12373/com.example.mattf.yankeetoyboxv1 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                  Process: com.example.mattf.yankeetoyboxv1, PID: 12373
                                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mattf.yankeetoyboxv1/com.example.mattf.yankeetoyboxv1.YourOrdersActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setSize(int)' on a null object reference
                                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setSize(int)' on a null object reference
                                                                                      at com.example.mattf.yankeetoyboxv1.SignInActivity.promptSignIn(SignInActivity.java:72)
                                                                                      at com.example.mattf.yankeetoyboxv1.SignInActivity.isUserSignedIn(SignInActivity.java:57)
                                                                                      at com.example.mattf.yankeetoyboxv1.SignInActivity.onCreate(SignInActivity.java:30)
                                                                                      at android.app.Activity.performCreate(Activity.java:7000)
                                                                                      at android.app.Activity.performCreate(Activity.java:6991)
                                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
                                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:106) 
                                                                                      at android.os.Looper.loop(Looper.java:164) 
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:6494) 
                                                                                      at java.lang.reflect.Method.invoke(Native Method) 
                                                                                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

最佳答案

您没有在 onCreate 方法中调用 setContentView(R.layout.your_orders_activity)

你的 onCreate 应该是这样的:

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

关于android - Google 登录按钮导致空对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724251/

相关文章:

java - 无法解决R无法解析为变量的问题

java - 在云中每隔几分钟运行一次 Java 应用程序的最佳方式?

java - 访问谷歌日历时出现空指针异常

java - 监听器中的 Firebase 监听器已跳过

android - Android 中短信和联系人的唯一标识符(检查重复)

java - Android NDK - 在不同的 header 中包含 C++ header ?

java - Azure 离线同步本地存储文档

android - 无法在 surfaceview 上绘制,因为 Canvas 为空

android - 使用Phonegap进行SDK开发

扩展 ParsePushBroadcastReceiver 通知的 Android 自定义类