0

I want to integrate Google sign in my app but it did not pursue me to another activity it shows the only authentication failed in emulator but when I test it on the real device there app stops on clicking google sign in button. Here is my code below

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

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.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class googleact extends AppCompatActivity {

SignInButton button;
FirebaseAuth firebaseauth;
private final static int RC_SIGN_IN=2;
GoogleApiClient mGoogleApiClient;
FirebaseAuth.AuthStateListener mAuthListener;


@Override
protected void onStart() {
    super.onStart();
    firebaseauth.addAuthStateListener(mAuthListener);
}

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


    button =(SignInButton) findViewById(R.id.googlebtn);
   firebaseauth = FirebaseAuth.getInstance();

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

    mAuthListener=new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser() !=null){

                startActivity(new Intent(googleact.this, gprofile.class));
            }
        }
    };

    // Configure Google Sign In
    GoogleSignInOptions gso = new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();


        // Build a GoogleApiClient with access to the Google Sign-In API and 
the
// options specified by gso.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, new 
    GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult 
    connectionResult) {
                    Toast.makeText(googleact.this,"something went wrong", 
    Toast.LENGTH_SHORT).show();
                }
            })
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

}


// Configure Google Sign In
//GoogleSignInOptions gso = new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  //     .requestIdToken(getString(R.string.default_web_client_id))
      //  .requestEmail()
      //  .build();


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

@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);
        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
        } else {
            Toast.makeText(googleact.this,"AUTH WENT WRONG", 
Toast.LENGTH_SHORT).show();
        }
    }
}

    private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
    AuthCredential credential = 
GoogleAuthProvider.getCredential(account.getIdToken(), null);
    firebaseauth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in 
user's information
                        Log.d("TAG", "signInWithCredential:success");
                        FirebaseUser user = firebaseauth.getCurrentUser();
                       // updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w("TAG", "signInWithCredential:failure", 
 task.getException());
                        Toast.makeText(googleact.this, "Authentication 
failed.",
                                Toast.LENGTH_SHORT).show();
                       // updateUI(null);
                    }

                    // ...
                }
            });

    }
}

here below is the logcat 07-02 13:55:11.367 24547-24547/? I/art: Not late-enabling -Xcheck:jni (already on) 07-02 13:55:11.367 24547-24547/? W/art: Unexpected CPU variant for X86 using defaults: x86 07-02 13:55:11.793 24547-24547/com.example.roomsarehere.foodishere W/System: ClassLoader referenced unknown path: /data/app/com.example.roomsarehere.foodishere-1/lib/x86 07-02 13:55:12.086 24547-24571/com.example.roomsarehere.foodishere I/DynamiteModule: Considering local module com.google.android.gms.flags:2 and remote module com.google.android.gms.flags:0 07-02 13:55:12.086 24547-24571/com.example.roomsarehere.foodishere I/DynamiteModule: Selected local version of com.google.android.gms.flags 07-02 13:55:12.131 24547-24571/com.example.roomsarehere.foodishere W/System: ClassLoader referenced unknown path: 07-02 13:55:12.136 24547-24571/com.example.roomsarehere.foodishere W/System: ClassLoader referenced unknown path: /system/priv- app/PrebuiltGmsCore/lib/x86 07-02 13:55:12.148 24547-24571/com.example.roomsarehere.foodishere D/ApplicationLoaders: ignored Vulkan layer search path /system/priv- app/PrebuiltGmsCore/lib/x86:/system/fake-libs:/system/priv- app/PrebuiltGmsCore/PrebuiltGmsCore.apk!/lib/x86:/system/lib:/vendor/lib for namespace 0xa787a090 07-02 13:55:12.194 24547-24547/com.example.roomsarehere.foodishere I/FA: App measurement is starting up, version: 11020 07-02 13:55:12.195 24547-24547/com.example.roomsarehere.foodishere I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE 07-02 13:55:12.222 24547-24571/com.example.roomsarehere.foodishere W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found. 07-02 13:55:12.265 24547-24547/com.example.roomsarehere.foodishere V/FA: Collection enabled

Wahdat Jan
  • 3,988
  • 3
  • 21
  • 46

2 Answers2

1
GoogleSignInOptions gso = new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build();

Write this part outside onCreate() and run the code and again rewrite same code in onCreate() commenting previous one and run probably it would do the job, I faced the same problem.

dswritter
  • 26
  • 1
  • 5
0
  1. Enable googleSignIn in Firebase console
  2. LoginActivity.java in your Android Studio -

    public class LoginActivity extends AppCompatActivity implements 
     GoogleApiClient.OnConnectionFailedListener{
    
    @BindView(R.id.sign_in_button)
    SignInButton signInButton;
    
    private FirebaseAuth mFirebaseAuth;
    private GoogleApiClient googleApiClient;
    private static int RC_SIGN_IN = 1;
    private DatabaseReference databaseReference;
    
    private ProgressDialog progressDialog;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    
        mFirebaseAuth = FirebaseAuth.getInstance();
    
        databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
        progressDialog = new ProgressDialog(this);
    
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(
                R.string.default_web_client_id))
                .requestEmail()
                .build();
        googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
                startActivityForResult(signInIntent, RC_SIGN_IN);
            }
        });
    }
    
    @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);
    
            progressDialog.setMessage("Signing in...");
            progressDialog.show();
    
            if (result.isSuccess()) {
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                progressDialog.dismiss();
                Log.e(LoginActivity.this.getClass().getSimpleName(), "Google Sign-In failed.");
            }
        }
    }
    
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(LoginActivity.this.getClass().getSimpleName(), "firebaseAuthWithGooogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mFirebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Log.d(LoginActivity.this.getClass().getSimpleName(), "signInWithCredential:onComplete:" + task.isSuccessful());
    
                if (!task.isSuccessful()) {
                    Log.w(LoginActivity.this.getClass().getSimpleName(), "signInWithCredential", task.getException());
                    Toast.makeText(LoginActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                } else {
                    progressDialog.dismiss();
                    checkUserExist();
                }
            }
        });
    }
    private void checkUserExist() {
    
        if(mFirebaseAuth.getCurrentUser() != null){
    
            final String user_id = mFirebaseAuth.getCurrentUser().getUid();
    
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
    
                    if(dataSnapshot.hasChild(user_id)){
                        Intent signinIntent = new Intent(LoginActivity.this,SplashActivity.class);
                        signinIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(signinIntent);
                    }
                    else{
                        Intent setupAccountIntent = new Intent(LoginActivity.this,SetupAccountActivity.class);
                        setupAccountIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(setupAccountIntent);
                    }
                }
    
                @Override
                public void onCancelled(DatabaseError databaseError) {
    
                }
            });
        }
    }
    
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_LONG).show();
    }
    

    }

So here in this activity when a user clicks on google sign in button, it gets authenticate on firebase console and go to the setup account where a user can set up their account like you can take details of user example profile pic, etc. Checking the user if he has set up the account then it will go to splash activity which is your launcher screen. Taking the user's data and save it in the database in "Users" node.

  1. SplashActivity.java - launcher screen

    public class SplashActivity extends AppCompatActivity {
    
    @BindView(R.id.start)
    Button start;
    
    private FirebaseAuth mFirebaseAuth;
    private FirebaseUser mFirebaseUser;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private GoogleApiClient googleApiClient;
    
    private DatabaseReference userDatabaseReference;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
    
        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseUser = mFirebaseAuth.getCurrentUser();
        userDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
    
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
                if (mFirebaseUser == null) {
                    Intent loginIntent = new Intent(SplashActivity.this,LoginActivity.class);
                    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(loginIntent);
                }
            }
        };
    
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Auth.GOOGLE_SIGN_IN_API , gso)
                .build();
    
        checkUserExist();
    }
    
    private void checkUserExist() {
    
        if(mFirebaseAuth.getCurrentUser() != null){
            final String user_id = mFirebaseAuth.getCurrentUser().getUid();
            userDatabaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
    
                    if(!dataSnapshot.hasChild(user_id)){
                        Intent setupAccountIntent = new Intent(SplashActivity.this,SetupAccountActivity.class);
                        setupAccountIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(setupAccountIntent);
                    }
                }
    
                @Override
                public void onCancelled(DatabaseError databaseError) {
    
                }
            });
        }
    }
    
    @Override
    public void onStart() {
        super.onStart();
        googleApiClient.connect();
        mFirebaseAuth.addAuthStateListener(mAuthListener);
    }
    
    @Override
    public void onStop() {
        if (mAuthListener != null) {
            mFirebaseAuth.removeAuthStateListener(mAuthListener);
        }
        googleApiClient.disconnect();
        super.onStop();
    }
    
    @OnClick(R.id.start)
    public void onViewClicked() {
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();
    }
    

    }

As this is my launcher activity, when user open the app if not authenticated then it will go to sign in and if account not set up then go to account setup activity.

Akshay Nandwana
  • 1,260
  • 11
  • 18
  • looks like you are doing 2 different work in same class( as you can see in the code I provided. 1.LoginActivity and other is the SplashActivity which is the launcher activity) So LoginActivity handle the google sign in button click and the launcher activity check if authenticate then continue else open LoginActivity – Akshay Nandwana Jul 02 '17 at 08:31
  • recommend doing the google button sign in part in login class and in your MainActivity, which a user will see after opening the application, check if user authenticate then ok else send the user to the login screen – Akshay Nandwana Jul 02 '17 at 08:35
  • @wahdatkashmiri hope [this](https://stackoverflow.com/questions/38106075/firebase-auth-not-working-update-google-play-services-msg-on-the-emulator-a) post helps you – Akshay Nandwana Jul 02 '17 at 08:39
  • Sir actually i have already written the code following google documentation i dont know what is the issue – Wahdat Jan Jul 02 '17 at 14:49