java - Google 登录按钮空指针异常

标签 java android nullpointerexception google-api-client google-signin

我正在尝试为我的应用程序实现 Google 登录按钮,虽然它最初运行,但我收到此错误:

09-16 19:44:38.679  26125-26125/com.hudsoncorp.zahudson.caravan E/AndroidRuntime? FATAL EXCEPTION: main
    Process: com.hudsoncorp.zahudson.caravan, PID: 26125
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference
            at com.hudsoncorp.zahudson.caravan.HomeActivity.onSignInClicked(HomeActivity.java:189)
            at com.hudsoncorp.zahudson.caravan.HomeActivity.onClick(HomeActivity.java:177)
            at com.google.android.gms.common.SignInButton.onClick(Unknown Source)
            at android.view.View.performClick(View.java:5156)
            at android.view.View$PerformClick.run(View.java:20755)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5835)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

我刚刚修复了一些使用 Google 登录的实现方法并遇到了这个问题。我对 Android 相当陌生,尤其是在实现 GoogleApiClients 方面。我想知道我的错误是否与我的方法顺序有关。再一次,我可能不知道我在说什么。我的 HomeActivity 代码是:

import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast;


import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.Scope; import com.google.android.gms.plus.Plus; import static android.view.View.*;


public class HomeActivity extends Activity implements
        ConnectionCallbacks,
        OnConnectionFailedListener,
        OnClickListener {

    private static final int RC_SIGN_IN = 0;
    private GoogleApiClient mGoogleApiClient;
    private Button mLoginButton;
    private TextView mSignUpLabel;

    /* Is there a ConnectionResult resolution in progress? */
    private boolean mIsResolving = false;

    /* Should we automatically resolve ConnectionResults when possible? */
    private boolean mShouldResolve = false;

    public static final String TAG = HomeActivity.class.getSimpleName();
    private TextView mStatusTextView;


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

        mLoginButton = (Button) findViewById(R.id.btnLogin);
        mLoginButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(HomeActivity.this, "Button Pressed", Toast.LENGTH_SHORT).show();
            }
        });

        mSignUpLabel = (TextView) findViewById(R.id.lblAboutUs);
        mSignUpLabel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(HomeActivity.this, "WAY TO SIGN UP MAN", Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.sign_in_button).setOnClickListener(this);

        // Build GoogleApiClient with access to basic profile
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API)
                .addScope(new Scope(Scopes.PROFILE))
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        // onConnected indicates that an account was selected on the device, that the selected
        // account has granted any requested permissions to our app and that we were able to 
        // establish a service connection to Google Play services.
        Log.d(TAG, "onConnected:" + bundle);
        mShouldResolve = false;

        //Show the signed-in UI
        showSignedInUI();
    }

    @Override
    public void onConnectionSuspended(int arg0) {

        // what should i do here ? should i call mGoogleApiClient.connect() again ? ?

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // Could not connect to Google Play Services.  The user needs to select an account,
        // grant permissions or resolve an error in order to sign in. Refer to the javadoc for
        // ConnectionResult to see possible error codes.

        Log.d(TAG, "onConnectionFailed:" + connectionResult);

        if (!mIsResolving && mShouldResolve) {
            if (connectionResult.hasResolution()) {
                try {
                    connectionResult.startResolutionForResult(this, RC_SIGN_IN);
                    mIsResolving = true;
                } catch (IntentSender.SendIntentException e) {
                    Log.e(TAG, "Could not resolve ConnectionResult.", e);
                    mIsResolving = false;
                    mGoogleApiClient.connect();
                }
            } else { //                // Could not resolve the connection result, show the user an //                // error dialog. //                showErrorDialog(connectionResult);
            }
        } else { //            // Show the signed-out UI //            showSignedOutUI();
        }
    }

//    private void showErrorDialog(ConnectionResult connectionResult) { // //    } // //    private void showSignedOutUI() { // //    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mGoogleApiClient.disconnect();
    }

    private void onSignInClicked() {
        // User clicked the sing-in button, so begin the sign-in process and automatically
        // attempt to resolve any errors that occur.
        mShouldResolve = true;
        mGoogleApiClient.connect();

        // Show a message to the user that we are signing in.
        mStatusTextView.setText(R.string.signing_in);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.sign_in_button) {
            onSignInClicked();
        }

    }

    private void showSignedInUI() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)  {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);

        if (requestCode == RC_SIGN_IN) {
            // If the error resolution was not successful we should not resolve it further.
            if (resultCode != RESULT_OK)  {
                mShouldResolve = false;
            }

            mIsResolving = false;
            mGoogleApiClient.connect();
        }
    }

}

最佳答案

您尚未使用 findViewByID 调用设置 mStatusTextView,因此它被绑定(bind)为 NULL。 在这个方法中:

protected void onCreate(Bundle savedInstanceState) {

您需要执行与其他小部件相同的操作:

mStatusTextView = (TextView) findViewById(R.id.TEXTVIEW_ID_HERE);

关于java - Google 登录按钮空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32683616/

相关文章:

java - Android 工作室抛出 IOException : Operation not permitted

android - 为什么我的 Intent 在我的应用程序的设置中打开应用程序信息,而不是我传递给它的 Activity 类?

java - setContentView 抛出 NullPointerException

java - 当抽象类具有 Final 字段时,lombok @Data 提示 "lombok needs a default constructor in the base class"

java - 面对日历对象的问题

java - Hbase Put 时间戳 (Java) 和 hbase shell 时间戳

java - 具有异常处理的方法的构建器模式

android - 如何使用 Google Drive API 上传文件?

java - 什么是 NullPointerException,我该如何解决?

java - NullPointerException:尝试在空对象引用 [Database Sqlite] 上调用虚拟方法