Google SIgn-In for android

[亡魂溺海] 提交于 2019-12-19 10:56:22

问题


I tried the google developer documentation and tried sign-in for my app. The code is copied from the git with added codes from the documentation. and defined in LoginActivity as

Public class LoginActivity extends AppCompatActivity implements
    GoogleApiClient.OnConnectionFailedListener,
    View.OnClickListener {

private static final String TAG = "* * SignIn * *";
private static final int RC_SIGN_IN = 9001;

private GoogleApiClient mGoogleApiClient;
private ProgressDialog mProgressDialog;
Bundle userData = new Bundle();
Intent newIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
   findViewById(R.id.sign_in_button).setOnClickListener(this);


    // [START configure_signin]
    // 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();
    // [END configure_signin]

    // [START build_client]
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    // [END build_client]

    // [START customize_button]
    SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
    signInButton.setSize(SignInButton.SIZE_STANDARD);
    signInButton.setScopes(gso.getScopeArray());
    // [END customize_button]
}

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

    OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
    if (opr.isDone()) {
        Log.d(TAG, "Got cached sign-in");
        GoogleSignInResult result = opr.get();
        handleSignInResult(result);
    } else {

        showProgressDialog();
        opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
            @Override
            public void onResult(GoogleSignInResult googleSignInResult) {
                hideProgressDialog();
                handleSignInResult(googleSignInResult);
            }
        });
    }
}

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

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    }
}
// [END onActivityResult]

// [START handleSignInResult]
private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount acct = result.getSignInAccount();
        userData.putString("Username", acct.getDisplayName());
        userData.putString("Email",acct.getEmail());
        newIntent = new Intent(LoginActivity.this, MainActivity.class);
        newIntent.putExtras(userData);
        startActivity(newIntent);
        finish();
    } else {
        userData.putString("Username", "Anonymous");
        userData.putString("Email","www.example.com");
        newIntent = new Intent(LoginActivity.this, MainActivity.class);
        newIntent.putExtras(userData);
        startActivity(newIntent);
        finish();
    }
}
// [END handleSignInResult]

// [START signIn]
private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}
// [END signIn]





@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
            Log.d(TAG, "onConnectionFailed:" + connectionResult);
}

private void showProgressDialog() {
    if (mProgressDialog == null) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Please wait");
        mProgressDialog.setIndeterminate(true);
    }

    mProgressDialog.show();
}

private void hideProgressDialog() {
    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        mProgressDialog.hide();
    }
}
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.sign_in_button:
            signIn();
            break;

    }
}

}

But I get following error log. as

12-16 23:02:44.074 5545-5545/com.example.www.newapp E/AndroidRuntime: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=40962, result=-1, data=Intent { (has extras) }} 
                                                                     to activity {com.example.www.newapp/com.google.android.gms.auth.api.signin.internal.SignInHubActivity}: 
                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference

My MainActivity code is as

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    View header = navigationView.getHeaderView(0);
    userName = (TextView) header.findViewById(R.id.userName);
    userName.setText(user);//Username recieved through intent
}}

While running it in emulator it shows update your play service, is it a problem?


回答1:


The Error occurred only in emulator in when compiling with new play service 8.3 While testing in actual hardware doesn't show any problem. It is due to the mismatch in the play service versions in emulator and the API. Hope they upgrade the Google API SDK with latest play service and release some notice about it.




回答2:


While you calling signIn() method ,method can't find startActivityForResult. where you got error.

You need to @override startActivityForResult for LoginActivity. Add below code in you LoginActivity.

Code:

 @Override
public void startActivityForResult(Intent intent, int requestCode) {
    super.startActivityForResult(intent, requestCode);
}


来源:https://stackoverflow.com/questions/34318888/google-sign-in-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!