6

I'm trying to authenticate with backend server from mobile app. I was following this documentation. https://developers.google.com/identity/sign-in/android/sign-in However, there are some errors. RC_SIGN_IN and updateUI() cannot be resolved.

My code is like this

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

    ...

       GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

       mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        mSignInButton = findViewById(R.id.sign_in_button);
        mSignInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_LONG).show();
            Intent signIntent = mGoogleSignInClient.getSignInIntent();
            startActivityForResult(signIntent, RC_SIGN_IN);
        }
    });


   @Override
   protected void onStart() {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        updateUI(account);
        super.onStart();
    }


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

    // Result returned 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 handleSignInResult(Task<GoogleSignInAccount> completedTask) {
       try {
           GoogleSignInAccount account = completedTask.getResult(ApiException.class);
           String idToken = account.getIdToken();

           // Send Id Token to the backend and validate here

           // Signed in successfully, show authenticated UI.
           updateUI(account);
       } catch (ApiException e) {
           // The ApiException status code indicates the detailed failure reason.
           // Please refer to the GoogleSignInStatusCodes class reference for more information.
           Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
           updateUI(null);
       }
   }

Update

Now the button itself doesn't work.

xml

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<!-- Include the main content -->
<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/text_view_result"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.v4.widget.NestedScrollView>

</FrameLayout>

<!-- Navigation bar -->
<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/navigation_menu"/>

</android.support.v4.widget.DrawerLayout>

How can I fix this?

11
  • Is the mSignInButton of type SignInButton
    – Gourav
    Feb 9, 2019 at 6:33
  • Yes I set private SignInButton mSignInButton;
    – user11016692
    Feb 9, 2019 at 6:35
  • Try removing the switch case, I have updated my answer.
    – Gourav
    Feb 9, 2019 at 6:35
  • Are you checking on emulator, if yes then you will first have to add a Google account there. Go to the gmail app there and add a Google account there.
    – Gourav
    Feb 9, 2019 at 6:38
  • I've removed switch statement and already my google account has added on my emulator but still doesn't work.
    – user11016692
    Feb 9, 2019 at 6:43

3 Answers 3

6

You need to do nothing but replace RC_SIGN_IN with an int value. It can be anything but use 1 as it's value. Do as follows:

startActivityForResult(signIntent, 1);

And change the if code in activity result as follows:

if (requestCode == 1)

Also change the sign in button click code to this(remove switch cases):

mSignInButton.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
                      signIn();
               }
           }
       });

This is because you are calling on click method to the button and then again checking If the same button is clicked, that's why I think it's not working.

Now for the updateUI method, this method should be defined by you. Basically, this is for your app to change what is shown to the user when he/she has signed into the app. If you want to open new activity when signedIn() you can use Intent by changing the updateUI(account) in the activity result and onstart event to an intent:

startActivity(new Intent(MainActivity.this, SecondActivity.class));

And get which account is signedin in the SecondActivity:

GoogleSignInAccount account = GoogleSignIn.g etLastSignedInAccount(this); //use this in onCreate
5
  • Thanks for answering. However sign_in_button itself doesn't work at all. I tried to set Toast inside OnClickListener but it doesn't show up.
    – user11016692
    Feb 9, 2019 at 6:22
  • Are you getting any null pointer reference or if the app crashes, can you please add the stack trace to the question?
    – Gourav
    Feb 9, 2019 at 6:23
  • Also please add where you define the button's Id and initialize it in the code
    – Gourav
    Feb 9, 2019 at 6:24
  • The app doesn't crash. The button itself just doesn't work.
    – user11016692
    Feb 9, 2019 at 6:37
  • Anyway thanks a lot for helping with patience. I upvote your answer.
    – user11016692
    Feb 9, 2019 at 7:17
3

Try this one.

In MainActivity, implement View.OnClickListener and GoogleApiClient.OnConnectionFailedListener

private static final String TAG = MainActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 007;
private GoogleApiClient mGoogleApiClient;

GoogleSignInOptions gso = new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

GoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());


private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount acct = result.getSignInAccount();

        Log.e(TAG, "display name: " + acct.getDisplayName());

        String personName = acct.getDisplayName();
        String personPhotoUrl = acct.getPhotoUrl().toString();
        String email = acct.getEmail();

        Log.e(TAG, "Name: " + personName + ", email: " + email
                + ", Image: " + personPhotoUrl);

        txtName.setText(personName);
        txtEmail.setText(email);
        Glide.with(getApplicationContext()).load(personPhotoUrl)
                .thumbnail(0.5f)
                .into(imgProfilePic);

        updateUI(true);
    } else {
        // Signed out, show unauthenticated UI.
        updateUI(false);
    }
}


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

private void signOut() {
    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    updateUI(false);
                }
            });
}


private void revokeAccess() {
    Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    updateUI(false);
                }
            });
}
@Override
public void onClick(View v) {
    int id = v.getId();

    switch (id) {
        case R.id.btn_sign_in:
            signIn();
            break;

        case R.id.btn_sign_out:
            signOut();
            break;

        case R.id.btn_revoke_access:
            revokeAccess();
            break;
    }

}


@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);
    }
}

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

    OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
    if (opr.isDone()) {
        // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
        // and the GoogleSignInResult will be available instantly.
        Log.d(TAG, "Got cached sign-in");
        GoogleSignInResult result = opr.get();
        handleSignInResult(result);
    } else {
        // If the user has not previously signed in on this device or the sign-in has expired,
        // this asynchronous branch will attempt to sign in the user silently.  Cross-device
        // single sign-on will occur in this branch.
        showProgressDialog();
        opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
            @Override
            public void onResult(GoogleSignInResult googleSignInResult) {
                hideProgressDialog();
                handleSignInResult(googleSignInResult);
            }
        });
    }
}

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

private void updateUI(boolean isSignedIn) {
    if (isSignedIn) {
        btnSignIn.setVisibility(View.GONE);
        btnSignOut.setVisibility(View.VISIBLE);
        btnRevokeAccess.setVisibility(View.GONE);
        llProfileLayout.setVisibility(View.VISIBLE);
    } else {
        btnSignIn.setVisibility(View.VISIBLE);
        btnSignOut.setVisibility(View.GONE);
        btnRevokeAccess.setVisibility(View.GONE);
        llProfileLayout.setVisibility(View.GONE);
    }
}
2
  • Actually I already tried to implement ViewOnClickListner and override OnClick method but still nothing happens.
    – user11016692
    Feb 9, 2019 at 7:58
  • I noticed a thing. Only the SignButton doesn't work. I tried with Button for signing in and it works.
    – user11016692
    Feb 10, 2019 at 10:24
3

RC_SIGN_IN is basically an int number code that is used to identify that your onActivityResult is called for google sign-in.

 private static final int RC_SIGN_IN = 007;

updateUi() is method used to let user know that google Signin is successfull or not. Here is method:

private void updateUI(GoogleSignInAccount signedIn) {
  if (signedIn != null) {
      // sigin is successfull
      signInButton.setVisibility(View.GONE);
      signOutButton.setVisibility(View.VISIBLE);
  } else {
      // sigin is cancelled
      signInButton.setVisibility(View.VISIBLE);
      signOutButton.setVisibility(View.GONE);
  }
}
1
  • Thanks the errors were fixed. However, sign_in_button doesn't work. Nothing happens when I click it.
    – user11016692
    Feb 9, 2019 at 5:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.