2

I have been following this tutorial to create a simple app with google sign in.

Tutorial link : http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/

I have followed the exact same steps mentioned in the tutorial. I have also generated the google-services.json file and placed it in the app folder.

When I click on the sign in button, accounts show up as shown in the below picture enter image description here

When an account is chosen, the control reaches to

public void onActivityResult(int requestCode, int resultCode, Intent data)

which contains

GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

the result is always not success. Can anyone let me know the possible reason?
Here is my mainActivity.java file.

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

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

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

    private GoogleApiClient mGoogleApiClient;
    private ProgressDialog mProgressDialog;

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

    @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);
        llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
        imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
        txtName = (TextView) findViewById(R.id.txtName);
        txtEmail = (TextView) findViewById(R.id.txtEmail);

        btnSignIn.setOnClickListener(this);
        btnSignOut.setOnClickListener(this);
        btnRevokeAccess.setOnClickListener(this);

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

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

        // Customizing G+ button
        btnSignIn.setSize(SignInButton.SIZE_STANDARD);
        btnSignIn.setScopes(gso.getScopeArray());
    }


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

    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)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imgProfilePic);

            updateUI(true);
        } else {
            // Signed out, show unauthenticated UI.
            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) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
    }

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

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.hide();
        }
    }

    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);
        }
    }
}
Minions
  • 1,273
  • 1
  • 11
  • 28

1 Answers1

0
    import com.bumptech.glide.Glide;
    import com.google.android.gms.auth.api.Auth;
    import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
    import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
    import com.google.android.gms.auth.api.signin.GoogleSignInResult;
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.SignInButton;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.OptionalPendingResult;
    import com.google.android.gms.common.api.ResultCallback;
    import com.google.android.gms.common.api.Status;
    import com.squareup.picasso.Picasso;
    import de.hdodenhof.circleimageview.CircleImageView;

    public class MainActivity extends AppCompatActivity
    implements AdapterView.OnItemSelectedListener, GoogleApiClient.OnConnectionFailedListener {

// ************************* GOOGLE *******************************
GoogleApiClient apiClient;
SignInButton btnSignIn;
//Button btnSignOut;
TextView txtNombre;
private static final int RC_SIGN_IN = 1001;
private ProgressDialog progressDialog;
private final Context mContext = this;
private CircleImageView mProfileImageView;

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

    txtNameGoogle = (TextView) findViewById(R.id.txtNombreGoogle);
    imgPhotoGoogle = (ImageView) findViewById(R.id.imgPhotoGoogle);

    // ************* GOOGLE **********************************
    btnSignOut= (Button) findViewById(R.id.sign_out_button);
    txtNombre   = (TextView) findViewById(R.id.txtNombreGoogle);
    btnSignIn = (SignInButton) findViewById(R.id.sign_in_button);
    mProfileImageView = (CircleImageView) findViewById(R.id.imgPhotoGoogle);
    //Google API Client
    GoogleSignInOptions gso =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .build();
    apiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    //Personalización del botón de login
    btnSignIn.setSize(SignInButton.SIZE_STANDARD);
    btnSignIn.setColorScheme(SignInButton.COLOR_AUTO);
    btnSignIn.setScopes(gso.getScopeArray());
    // *********************** Boton Google *****************************************
    btnSignIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(apiClient);
                startActivityForResult(signInIntent, RC_SIGN_IN);
        }
    });
    btnSignOut.setOnClickListener(new View.OnClickListener() {  
        @Override   
        public void onClick(View v) {   
            Auth.GoogleSignInApi.signOut(apiClient).setResultCallback(  
                    new ResultCallback<Status>() {  
                        @Override   
                        public void onResult(Status status) {   
                            updateUI(false);    
                        }   
                    }); 
        }   
    });
    updateUI(false);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Toast.makeText(this, "Error de conexion!", Toast.LENGTH_SHORT).show();
    Log.e("GoogleSignIn", "OnConnectionFailed: " + connectionResult);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result =
                Auth.GoogleSignInApi.getSignInResultFromIntent(data);

        handleSignInResult(result);
    }
}

private void handleSignInResult(GoogleSignInResult result) {
    if (result.isSuccess()) {
        //Usuario logueado --> Mostramos sus datos
        GoogleSignInAccount acct = result.getSignInAccount();
        txtNombre.setText(acct.getDisplayName());
        //txtEmail.setText(acct.getEmail());
        //txtId.setText(acct.getId());
        //txtId.setText(acct.getPhotoUrl().toString());
        Uri uri = acct.getPhotoUrl();
        Picasso.with(mContext)
                .load(uri)
                .placeholder(R.drawable.common_google_signin_btn_icon_dark_pressed)
                .error(R.drawable.common_google_signin_btn_icon_dark)
                .into(mProfileImageView);
        updateUI(true);
    } else {
        //Usuario no logueado --> Lo mostramos como "Desconectado"
        updateUI(false);
    }
}
private void updateUI(boolean signedIn) {
    if (signedIn) {
        btnSignIn.setVisibility(View.GONE);
        txtNombre.setVisibility(View.VISIBLE);
        mProfileImageView.setVisibility(View.VISIBLE);
    } else {
        txtNombre.setText("Desconectado");
        mProfileImageView.setImageResource(R.drawable.common_google_signin_btn_icon_dark_disabled);

        txtNombre.setVisibility(View.GONE);
        mProfileImageView.setVisibility(View.GONE);
        btnSignIn.setVisibility(View.VISIBLE);
    }
}

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

    OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(apiClient);
    if (opr.isDone()) {
        GoogleSignInResult result = opr.get();
        handleSignInResult(result);
    } else {
        showProgressDialog();
        opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
            @Override
            public void onResult(GoogleSignInResult googleSignInResult) {
                hideProgressDialog();
                handleSignInResult(googleSignInResult);
            }
        });
    }
}

private void showProgressDialog() {
    if (progressDialog == null) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("SignI-In");
        progressDialog.setIndeterminate(true);
    }

    progressDialog.show();
}

private void hideProgressDialog() {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.hide();
    }
}
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • 2
    Please reword your explanation so that it is in English. Please read the SO guidelines before posting. – sparkitny Apr 05 '18 at 04:23