I'm making a login activity that has a Sign in with Google Button
I am using a Firebase Auth to provide a Google sign-in method. I am following this documentation from firebase. I already follow along with the documentation, but my apps keep stoping. Why this problem occured? I've watched so many tutorials and searched for the same problem in Google. But I can't solve this problem. Here is my LoginActivity
and the activity_login.xml
code.
Edit
After sawing the logcat, the Google Mobile Ads SDK was initialized incorrectly. Here's the logcat
******************************************************************************
* The Google Mobile Ads SDK was initialized incorrectly. AdMob publishers *
* should follow the instructions here: *
* https://googlemobileadssdk.page.link/admob-android-update-manifest *
* to add a valid App ID inside the AndroidManifest. *
* Google Ad Manager publishers should follow instructions here: *
* https://googlemobileadssdk.page.link/ad-manager-android-update-manifest. *
******************************************************************************
at com.google.android.gms.ads.internal.client.zzef.attachInfo(com.google.android.gms:play-services-ads-lite@@21.0.0:20)
at com.google.android.gms.ads.MobileAdsInitProvider.attachInfo(com.google.android.gms:play-services-ads-lite@@21.0.0:1)
at android.app.ActivityThread.installProvider(ActivityThread.java:7488)
... 11 more
@Suppress("DEPRECATION")
class LoginActivity : AppCompatActivity() {
private lateinit var oneTapClient: SignInClient
private lateinit var signInReq: BeginSignInRequest
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var auth: FirebaseAuth
private val REQ_ONE_TAP = 1 // Can be any integer unique to the Activity
private var showOneTapUI = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
// [START config_signin]
// Configure Google Sign In
val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions)
// [END config_signin]
// [START init_auth]
// Initialize Firebase Auth
auth = Firebase.auth
// [END init_auth]
oneTapClient = Identity.getSignInClient(this)
oneTapClient.beginSignIn(signInReq)
.addOnSuccessListener(this) { result ->
try {
startIntentSenderForResult(
result.pendingIntent.intentSender, REQ_ONE_TAP,
null, 0, 0, 0, null
)
} catch (e: IntentSender.SendIntentException) {
Log.e(TAG, "Couldn't start One Tap UI: ${e.localizedMessage}")
}
}
.addOnFailureListener(this) { e ->
// No saved credentials found. Launch the One Tap sign-up flow, or
// do nothing and continue presenting the signed-out UI
Log.d(TAG, e.localizedMessage as String)
}
signInReq = BeginSignInRequest.builder()
.setPasswordRequestOptions(
BeginSignInRequest.PasswordRequestOptions.builder()
.setSupported(true)
.build())
.setGoogleIdTokenRequestOptions(
BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
.setSupported(true)
// Your server's client ID, not your android client ID
.setServerClientId(getString(R.string.default_web_client_id))
// Only show accounts previously used to sign in
.setFilterByAuthorizedAccounts(true)
.build())
.build()
val googleButton: Button = findViewById(R.id.btnGoogleLogin)
googleButton.setOnClickListener {
// TODO: Implement Google Sign In
}
// [START click_textview]
// Set the footer text view to be clickable
val tvFooter: TextView = findViewById(R.id.txtFooterLogin)
val foregroundColorSpan = ForegroundColorSpan(getColor(R.color.pickled_bluewood))
val boldSpan = StyleSpan(Typeface.BOLD)
val spannableString = SpannableString(tvFooter.text.toString())
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
val intent = Intent(this@LoginActivity, HomeActivity::class.java)
startActivity(intent)
}
override fun updateDrawState(drawState: TextPaint) {
super.updateDrawState(drawState)
drawState.isUnderlineText = true
}
}
spannableString.setSpan(boldSpan, 23, spannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
spannableString.setSpan(foregroundColorSpan, 23, spannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
spannableString.setSpan(clickableSpan, 23, spannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
tvFooter.text = spannableString
tvFooter.movementMethod = LinkMovementMethod.getInstance()
// [END click_textview]
}
override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQ_ONE_TAP -> {
try {
val googleCredential = oneTapClient.getSignInCredentialFromIntent(data)
val idToken = googleCredential.googleIdToken
// val username = googleCredential.id
val password = googleCredential.password
when {
idToken != null -> {
// Got an ID token from Google. Use it to authenticate
// with your backend
val firebaseCredential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(firebaseCredential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show()
updateUI(null)
}
}
}
password != null -> {
// Got a saved username and password. Use them to authenticate
// with your backend
Log.d(TAG, "Got password")
}
else -> {
// Shouldn't happen
Log.d(TAG, "Not ID token or password!")
}
}
} catch (e: ApiException) {
// Handle error
when (e.statusCode) {
CommonStatusCodes.CANCELED -> {
Log.d(TAG, "One-tap dialog was closed.")
// Don't re-prompt the user
showOneTapUI = false
}
CommonStatusCodes.NETWORK_ERROR -> {
Log.d(TAG, "One-tap encountered a network error.")
// Try again or just ignore
}
else -> {
Log.d(TAG, "Couldn't get credential from result: ${e.localizedMessage}")
}
}
}
}
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential: AuthCredential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
Toast.makeText(baseContext, "Authentication Failed.", Toast.LENGTH_SHORT).show()
updateUI(null)
}
}
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
private fun signOut() {
// Firebase sign out
auth.signOut()
// Google sign out
googleSignInClient.signOut().addOnCompleteListener(this) {
updateUI(null)
}
}
private fun updateUI(currentUser: FirebaseUser?) {
if (currentUser != null) {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
// else {
// oneTapClient.beginSignIn(signInReq)
// .addOnSuccessListener { pendingIntent ->
// startIntentSenderForResult(pendingIntent.intentSender, 1001, null, 0, 0, 0, null)
// }
// .addOnFailureListener { e ->
// // Handle error
// }
// }
}
companion object {
private const val TAG = "GoogleActivity"
private const val RC_SIGN_IN = 9001
}
}