java - 如何修复 Android 上 G+ 中的 boolean com.google.android.gms.common.ConnectionResult.hasResolution() Null 引用

标签 java android

我想使用 Google Plus 帐户登录我的应用程序。我编写了此代码,但显示强制关闭错误。
主要 Activity 代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "MainActivity";
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;

private boolean mIntentInProgress;

private boolean mSignInClicked;

private ConnectionResult mConnectionResult;

private SignInButton btnSignIn;
private Button btnSignOut, btnRevokeAccess;
private TextView txtName, txtEmail;
private LinearLayout llProfileLayout;

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

    btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
    btnSignOut = (Button) findViewById(R.id.btn_sign_out);
    btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
    txtName = (TextView) findViewById(R.id.txtName);
    txtEmail = (TextView) findViewById(R.id.txtEmail);
    llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);

    // Button click listeners
    btnSignIn.setOnClickListener(this);
    btnSignOut.setOnClickListener(this);
    btnRevokeAccess.setOnClickListener(this);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_LOGIN)
            .build();
}

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

protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

/**
 * Method to resolve any signin errors
 */
private void resolveSignInError() {
    if (mConnectionResult.hasResolution()) {
        try {
            mIntentInProgress = true;
            mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
        } catch (SendIntentException e) {
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    if (!result.hasResolution()) {
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
                0).show();
        return;
    }

    if (!mIntentInProgress) {
        // Store the ConnectionResult for later usage
        mConnectionResult = result;

        if (mSignInClicked) {
            // The user has already clicked 'sign-in' so we attempt to
            // resolve all
            // errors until the user is signed in, or they cancel.
            resolveSignInError();
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int responseCode,
                                Intent intent) {
    if (requestCode == RC_SIGN_IN) {
        if (responseCode != RESULT_OK) {
            mSignInClicked = false;
        }

        mIntentInProgress = false;

        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    }
}

@Override
public void onConnected(Bundle arg0) {
    mSignInClicked = false;
    Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();

    // Get user's information
    getProfileInformation();

    // Update the UI after signin
    updateUI(true);

}

/**
 * Updating the UI, showing/hiding buttons and profile layout
 */
private void updateUI(boolean isSignedIn) {
    if (isSignedIn) {
        btnSignIn.setVisibility(View.GONE);
        btnSignOut.setVisibility(View.VISIBLE);
        btnRevokeAccess.setVisibility(View.VISIBLE);
        llProfileLayout.setVisibility(View.VISIBLE);
    } else {
        btnSignIn.setVisibility(View.VISIBLE);
        btnSignOut.setVisibility(View.GONE);
        btnRevokeAccess.setVisibility(View.GONE);
        llProfileLayout.setVisibility(View.GONE);
    }
}

/**
 * Fetching user's information name, email, profile pic
 */
private void getProfileInformation() {
    try {
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
            Person currentPerson = Plus.PeopleApi
                    .getCurrentPerson(mGoogleApiClient);
            String personName = currentPerson.getDisplayName();
            String personGooglePlusProfile = currentPerson.getUrl();
            String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

            Log.e(TAG, "Name: " + personName + ", plusProfile: "
                    + personGooglePlusProfile + ", email: " + email);

            txtName.setText(personName);
            txtEmail.setText(email);

            // by default the profile url gives 50x50 px image only
            // we can replace the value with whatever dimension we want by
            // replacing sz=X

        } else {
            Toast.makeText(getApplicationContext(),
                    "Person information is null", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onConnectionSuspended(int arg0) {
    mGoogleApiClient.connect();
    updateUI(false);
}

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

/**
 * Button on click listener
 */
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_sign_in:
            // Signin button clicked
            signInWithGplus();
            break;
        case R.id.btn_sign_out:
            // Signout button clicked
            signOutFromGplus();
            break;
        case R.id.btn_revoke_access:
            // Revoke access button clicked
            revokeGplusAccess();
            break;
    }
}

/**
 * Sign-in into google
 */
private void signInWithGplus() {
    if (!mGoogleApiClient.isConnecting()) {
        mSignInClicked = true;
        resolveSignInError();
    }
}

/**
 * Sign-out from google
 */
private void signOutFromGplus() {
    if (mGoogleApiClient.isConnected()) {
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();
        updateUI(false);
    }
}

/**
 * Revoking access from google
 */
private void revokeGplusAccess() {
    if (mGoogleApiClient.isConnected()) {
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status arg0) {
                        Log.e(TAG, "User access revoked!");
                        mGoogleApiClient.connect();
                        updateUI(false);
                    }

                });
    }
}

}

强制关闭错误:

05-21 11:08:13.007 32103-32103/com.tellfa.googlepluslogin E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.tellfa.googlepluslogin, PID: 32103
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.common.ConnectionResult.hasResolution()' on a null object reference
                                                                                at com.tellfa.googlepluslogin.MainActivity.resolveSignInError(MainActivity.java:84)
                                                                                at com.tellfa.googlepluslogin.MainActivity.signInWithGplus(MainActivity.java:234)
                                                                                at com.tellfa.googlepluslogin.MainActivity.onClick(MainActivity.java:215)
                                                                                at com.google.android.gms.common.SignInButton.onClick(Unknown Source)
                                                                                at android.view.View.performClick(View.java:4764)
                                                                                at android.view.View$PerformClick.run(View.java:19844)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5349)
                                                                                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:908)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

如何解决这个问题?

我想使用 Google Plus 帐户登录我的应用程序。我编写了此代码,但显示强制关闭错误。

最佳答案

您的字段mConnectionResult 可以为 null,这会导致应用在尝试访问它时抛出 NullPointerException。

解决方案是更改 onConnectionFailed 的处理方式这样它总是在您访问变量之前为其分配一个值。

@Override
public void onConnectionFailed(ConnectionResult result) {
    // Always assign result first
    mConnectionResult = result;

    if (!result.hasResolution()) {
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
                0).show();
        return;
    }

    if (!mIntentInProgress) {

        if (mSignInClicked) {
            // The user has already clicked 'sign-in' so we attempt to
            // resolve all
            // errors until the user is signed in, or they cancel.
            resolveSignInError();
        }
    }
}

关于java - 如何修复 Android 上 G+ 中的 boolean com.google.android.gms.common.ConnectionResult.hasResolution() Null 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37359863/

相关文章:

java - Guava:是否可以不使用 Multimaps.index() 映射所有条目?

java - 如何计算有符号随机整数的绝对值

android - 我是否必须使用 Android 中的加速度计才能让我的照片正确定位?

Android Studio 无法在应用程序上显示版本号

android - 更改 RecyclerView 网格布局中的列数

android - 如何在工具栏中的菜单旁边添加微调器

java - 添加到检索到的 ArrayList

java - 三元运算符语句上的表达式开始非法

java - 为什么 protected 实例成员在不同包的子类中不可见,但 protected 类成员是?

android - 使用不带 String.xml 的 FontAwesome 从代码动态设置字体图标