1

I am integrating google sign-in into my android project using Firebase. Following this tutorial, I was able to get the login. But when I choose the account, the app crashes.

By the way I am using Kotlin language.

The code snippet is as follows:

class SignupActivity:AppCompatActivity(){

lateinit var googleSignInClient: GoogleSignInClient
lateinit var gso: GoogleSignInOptions
val RC_SIGN_IN :Int =1
lateinit var signOut:Button
lateinit var mAuth: FirebaseAuth

private var callbackManager: CallbackManager?=null
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.signup)
    header_signup_button.setOnClickListener {
        startActivity(Intent(this,SplashscreenActivity::class.java))
    }
    gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build()
    googleSignInClient = GoogleSignIn.getClient(this,gso)
    mAuth = FirebaseAuth.getInstance()
    signOut = findViewById<View>(R.id.signOutBtn) as Button
    signOut.visibility= View.INVISIBLE
    google_signup.setOnClickListener {
        view:View?->signInGoogle()
    }
    signupemail_button.setOnClickListener {
        startActivity(Intent(this,EmailSignupActivity::class.java))
    }

    val fblogin_button= findViewById<Button>(R.id.facebook_signup)
    fblogin_button.setOnClickListener {
        callbackManager = CallbackManager.Factory.create()
        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email"))
        if (!isloggedIn()) {
            LoginManager.getInstance().registerCallback(callbackManager,
                    object : FacebookCallback<LoginResult> {
                        override fun onSuccess(loginResult: LoginResult) {
                            Log.d("LoginActivity", "Facebook token" + loginResult.accessToken.token)
                            startActivity(Intent(baseContext, MainActivity::class.java))
                        }

                        override fun onCancel() {
                            Log.d("LoginActivity", "Facebook oncancel")
                        }

                        override fun onError(error: FacebookException?) {
                            Log.d("LoginActivity", "Facebook onError")
                        }
                    })
        } else {
            LoginManager.getInstance().unregisterCallback(callbackManager, object : FacebookCallback<LoginResult> {
                override fun onSuccess(result: LoginResult?) {
                    GraphRequest(AccessToken.getCurrentAccessToken(), "/{user-id}/permissions/", null, HttpMethod.DELETE, GraphRequest.Callback() {
                        AccessToken.setCurrentAccessToken(null)
                        LoginManager.getInstance().logOut()
                    }).executeAsync()
                    Log.d("LoginActivity", "Facebook token" + result?.accessToken?.token)
                }

                override fun onCancel() {
                    Log.d("LoginActivityunregister", "Facebook oncancel")
                }

                override fun onError(error: FacebookException?) {
                    Log.d("LoginActivityunregister", "Facebook onError")
                }

            })
        }
    }
}

private fun signInGoogle() {
    val signIntent:Intent =googleSignInClient.signInIntent
    startActivityForResult(signIntent,RC_SIGN_IN)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == RC_SIGN_IN) {
    if (resultCode!= Activity.RESULT_OK) {
            val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
        try {
            val account = task.getResult()
            val credential = GoogleAuthProvider.getCredential(account.idToken,null)
            mAuth.signInWithCredential(credential)
                    .addOnCompleteListener(this, OnCompleteListener<AuthResult>(){
                        if (task.isSuccessful) {
                            val user = mAuth.currentUser
                            if (user != null) {
                                updateUI(user)
                            }
                        }else{
                            updateUI(null)
                        }
                    })
        }catch (e:ApiException){
            Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show()
        }

        }
    }
    else {
        callbackManager?.onActivityResult(requestCode, resultCode, data)
    }
}
private fun updateUI(user: FirebaseUser?) {
    val disptext = findViewById<View>(R.id.disptxt) as TextView
    if (user != null) {
        disptext.text = user.displayName
    }
    signOut.visibility=View.VISIBLE
    signOut.setOnClickListener { view:View->
        googleSignInClient.signOut().addOnCompleteListener {
            task -> disptext.text = " "
            signOut.visibility= View.INVISIBLE
        }
    }
}

@SuppressLint("NewApi")
override fun onBackPressed() {
    super.onBackPressed()
    startActivity(Intent(this,SplashscreenActivity::class.java))
  }
}
private fun Any.unregisterCallback(callbackManager: CallbackManager?, facebookCallback: FacebookCallback<LoginResult>) {

}

fun isloggedIn(): Boolean {
val accessToken = AccessToken.getCurrentAccessToken()
return accessToken != null
}

The manifest file: In the manifest file I have added the metadata.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.vishwa.imaginators">
<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/myicon"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".SplashscreenActivity"
        android:theme="@style/AppTheme"
        android:noHistory="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".LoginActivity">
    </activity>
    <activity android:name=".SigninActivity">
    </activity>
    <activity android:name=".SignupActivity">
    </activity>
    <activity android:name=".EmailSignupActivity">
    </activity>
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id" />

    <activity android:name="com.facebook.FacebookActivity"
        android:configChanges=
            "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name"/>
    <activity android:name=".MainActivity">

    </activity>
 </application>

 </manifest>

The error that comes is Caused by: com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 10. I have looked up this issue and no answer solves my problem.

I'm posting the error log as well for more clarity.

FATAL EXCEPTION: main
              Process: com.example.vishwa.imaginators, PID: 27350
              java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=Intent { (has extras) }} to activity {com.example.vishwa.imaginators/com.example.vishwa.imaginators.SignupActivity}: com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 10: 
                  at android.app.ActivityThread.deliverResults(ActivityThread.java:3772)
                  at android.app.ActivityThread.handleSendResult(ActivityThread.java:3815)
                  at android.app.ActivityThread.access$1500(ActivityThread.java:154)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:157)
                  at android.app.ActivityThread.main(ActivityThread.java:5571)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
               Caused by: com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 10: 
                  at com.google.android.gms.tasks.zzu.getResult(Unknown Source)
                  at com.example.vishwa.imaginators.SignupActivity.onActivityResult(SignupActivity.kt:117)
                  at android.app.Activity.dispatchActivityResult(Activity.java:6562)
                  at android.app.ActivityThread.deliverResults(ActivityThread.java:3768)
                  at android.app.ActivityThread.handleSendResult(ActivityThread.java:3815) 
                  at android.app.ActivityThread.access$1500(ActivityThread.java:154) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:157) 
                  at android.app.ActivityThread.main(ActivityThread.java:5571) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635) 
               Caused by: com.google.android.gms.common.api.ApiException: 10: 
                  at com.google.android.gms.common.internal.ApiExceptionUtil.fromStatus(Unknown Source)
                  at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
                  at com.example.vishwa.imaginators.SignupActivity.onActivityResult(SignupActivity.kt:115)
                  at android.app.Activity.dispatchActivityResult(Activity.java:6562) 
                  at android.app.ActivityThread.deliverResults(ActivityThread.java:3768) 
                  at android.app.ActivityThread.handleSendResult(ActivityThread.java:3815) 
                  at android.app.ActivityThread.access$1500(ActivityThread.java:154) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:157) 
                  at android.app.ActivityThread.main(ActivityThread.java:5571) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635) 

Moreover, you'll also notice that I have Facebook sign-in integration as well for my project. But now that too is not working after adding the google sign-in. Therefore I am looking forward to some help. Any help is appreciated.

Eswar
  • 1,201
  • 19
  • 45
  • Please add your manifest file. – Alex Mamo Jul 31 '18 at 14:19
  • @AlexMamo I have edited the question including the manifest file. – Eswar Jul 31 '18 at 14:23
  • Error code 10 usually indicates a problem with your SHA1 fingerprint. See Sam Stern's comment at [this post](https://github.com/googlesamples/google-services/issues/360). – Bob Snyder Jul 31 '18 at 14:31
  • @BobSnyder I have posted the error logs, can you still say its because of the SHA1 finger print. I am asking because when I follow this link https://developers.google.com/identity/sign-in/android/start-integrating., I get an error with the fingerprint. I then shifted to using firebase where I gave SHA-256. The app builds and doesn't crash until I choose the google account. However, the same was not possible without using the firebase. I could get the google services json file itself. – Eswar Aug 01 '18 at 05:47
  • have you configured google sign in properly? please verify SHA key is properly installed. – Jay Dangar Aug 01 '18 at 05:53
  • @JayDangar In the assistant window of firebase/authentication, it says that I have to connect to firebase and I am unable to coonect to firebase where as the dependencies are setup correctly. What does this hint to? – Eswar Aug 01 '18 at 06:10

1 Answers1

1

Your AndroidManifest.XML looks correct to me. I encountered the same error:

Caused by: com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 10

Which basically means that you are providing an unknown server client id. In Google Developer Console, select your project you generate: OAuth client ID -> Web Application and use this web application client id in your Android app.

Edit:

I definitely know that the problem is in the SHA1 key that you add to the Firebase Console. So you can regenerate it and put it again properly in the same project. Please also make sure that:

1) Your actual signed Android apk has the same SHA1 fingerprint as the one specified in the Firebase Console of your project. See Android integration section, the page where you can download the google-services.json.

2) Your Firebase project is linked with Google Play. For that go on top of page to Project Overview then go to the Project Settings (gear icon), then go Integration tab. On that tab link the Google Play to your project.

The last one should solve your problem.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Where should the manifest file be modified? If I copy the client Id to the values field I get an error of duplicacy. – Eswar Jul 31 '18 at 14:58
  • Of duplicity? Do you antoher OAuth client ID? Change it with the one from your Google Developer Console. – Alex Mamo Jul 31 '18 at 15:04
  • Have you also tried what Bob Snyder mentioned in his comment? – Alex Mamo Jul 31 '18 at 15:05
  • If there is already an API key, just let it in the place it is and change it with the one from Google Developer Console. – Alex Mamo Jul 31 '18 at 15:15
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177113/discussion-between-eswar-and-alex-mamo). – Eswar Jul 31 '18 at 15:18
  • No. I'm unable to fix. But in attempting I realize that I am not connected to the firebase as shown in the android assistant. What does this hint to? – Eswar Aug 01 '18 at 09:07