google authentication pop up not working using firebase in android development - android

while doing a project...i did an authentication with a google account. but it's not working
MainActivity.kt in this activity I have implemented authentication uisng firebase but when i click the button no popup is showing
class MainActivity : AppCompatActivity() {
private lateinit var mAuth: FirebaseAuth
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var binding: ActivityMainBinding
companion object{
private const val RC_SIGN_IN = 120
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(R.layout.activity_main)
// Configure Google Sign In
val 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()
binding.gbutton.setOnClickListener{
signIn()
}
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
val exception = task.exception
if(task.isSuccessful){
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d("SignInActivity", "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w("SignInActivity", "Google sign in failed", e)
}
}
else{
Log.w("SignInActivity", exception.toString())
}
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d("SignInActivity", "signInWithCredential:success")
val intent = Intent(this,ActivityGoogleSigninBinding::class.java)
startActivity(intent)
finish()
} else {
// If sign in fails, display a message to the user.
Log.d("SignInActivity", "signInWithCredential:failure", task.exception)
}
}
}
}
Gradle scripts and buttonID (using binding, XML file in layout) are done correctly
I have also checked logcat but couldn't found any error
Please help

Related

Where do if put my Check Box if statement in Login Activity?

Hope you are well.
I would like to add a Check Box (I am 18+ Years Old) on my Login Activity (using Google Login) for my Android App.
It is working in a way: It continues to the Google Login Option (asking for your Email), then comes back to Login Activity again if not checked. Then shows the toast. So it works in a way.
I would like it to show the toast until the Box is Checked, then open the Email block to ask for your email.
Another problem is now it always returns to this screen when the app starts. But it does remember the user and doesn't ask for the email details again. I want it only once along with the Google Login.
What I'm really asking is please where should my check box if statement be? Please help.
It is now after:
private fun updateUI(user: FirebaseUser?) {
Here is a Pastebin link just in incase:
https://pastebin.com/GPC2X3xJ
Here is the Login Activity:
class LoginActivity : AppCompatActivity() {
private companion object {
private const val TAG = "LoginActivity"
private const val RC_GOOGLE_SIGN_IN= 4915
}
private lateinit var auth: FirebaseAuth
private lateinit var checkBox: CheckBox
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
auth = Firebase.auth
// Configure Google Sign In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
val client = GoogleSignIn.getClient(this, gso)
findViewById<View>(R.id.btnSignIn)?.setOnClickListener {
val signInIntent = client.signInIntent
startActivityForResult(signInIntent, RC_GOOGLE_SIGN_IN)
}
}
override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
private fun updateUI(user: FirebaseUser?) {
//Navigate to MainActivity
if (user == null){
Log.w(TAG, "User is null, not going to navigate")
return
} else {
val mCheckBox = findViewById<CheckBox>(R.id.check_box_18)
if (mCheckBox.isChecked) {
startActivity(Intent(this, MainActivity::class.java))
finish()
} else {
Toast.makeText(
applicationContext,
"Please confirm you are 18+ years old",
Toast.LENGTH_SHORT
).show()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_GOOGLE_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d(TAG, "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
}
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = 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(this, "Authentication Failed", Toast.LENGTH_SHORT).show()
updateUI(null)
}
I think you can make validation inside the button sign in here
findViewById<View>(R.id.btnSignIn)?.setOnClickListener { val signInIntent = client.signInIntent startActivityForResult(signInIntent, RC_GOOGLE_SIGN_IN)},
if the checkbox is not checked you can show the toast,
val signInIntent = client.signInIntent startActivityForResult(signInIntent, RC_GOOGLE_SIGN_IN)}`,
make this code inside validation

After signing out with firebase google, I sign in again. All the data I keep in the database is deleted

I want it to log in with google to keep users favorite words in my app. When the user exits the application, the user comes back to the login page with google. And all the user's favorite words are deleted. how can I solve this problem Below I show the deleted parts?
class SignInActivity : AppCompatActivity() {
companion object {
private const val RC_SIGN_IN = 120
}
private lateinit var mAuth: FirebaseAuth
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var database: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
val sign_in_btn : Button = findViewById(R.id.sign_in_btn)
// Configure Google Sign In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
database = Firebase.database.reference
//Firebase Auth instance
mAuth = FirebaseAuth.getInstance()
sign_in_btn.setOnClickListener {
signIn()
}
}
private fun writeNewUser(userId: String, name: String, email: String) {
val user = Users(userId, name, email)
database.child("users").child(userId).setValue(user)
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN) }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
val exception = task.exception
if(task.isSuccessful){
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d(ContentValues.TAG, "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(ContentValues.TAG, "Google sign in failed", e)
}
}else{
Log.w(ContentValues.TAG, exception.toString())
}
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = mAuth.currentUser
writeNewUser(user?.uid.toString(), user?.displayName.toString(),
user?.email.toString()
)
// Sign in success, update UI with the signed-in user's information
Log.d(ContentValues.TAG, "signInWithCredential:success")
val intent = Intent(this, DashboardActivity::class.java)
startActivity(intent)
finish()
} else {
// If sign in fails, display a message to the user.
Log.w(ContentValues.TAG, "signInWithCredential:failure", task.exception) }
}
}
}
And my SignOut function
sign_out_btn.setOnClickListener {
mAuth.signOut()
val intent = Intent(this,SignInActivity::class.java)
startActivity(intent)
finish()
}
You are always getting everything wiped out because when you perform a successful Firebase authentication with Google you always call writeNewUser() method, which actually performs a write operation in the database using the following line of code:
database.child("users").child(userId).setValue(user)
So this actually means that you always write the user object on the existing one. Surprising, this is not what you want. To solve this, you need to check if the user already exists in the database before performing a new write operation. So please check my answer from the following post:
Checking if a particular value exists in the Firebase database
So you only need to write user data if it doesn't already exist.

firebase google sign in result code is always 0

I wanted to integrate google sign In in my app using firebase and I followed all the instructions from enabling google sign In in my firebase console and adding SHA-1 certificate fingerprint and adding the google-services.json file in the app directory.
But whenever I am trying to sign In after selecting the google account the response code is coming out be 0 always and hence unable to sign In.
Here is the Code:-
class SignInActivity : AppCompatActivity() {
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var auth:FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
val gso= GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this,gso)
signInButton.setOnClickListener {
resultLauncher.launch(googleSignInClient.signInIntent)
}
}
private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){result->
Log.i("resultCode",result.resultCode.toString())
val intent=result.data
Log.i("intentData",intent.toString())
if(result.resultCode == Activity.RESULT_OK)
{
Log.i("resultCode","reachedHere")
val task = GoogleSignIn.getSignedInAccountFromIntent(intent)
handleSignInResult(task)
}
else{
Log.i("unsuccessfulSignIN",result.resultCode.toString())
}
}
private fun handleSignInResult(task: Task<GoogleSignInAccount>?) {
try{
val account= task?.getResult(ApiException::class.java)!!
Log.i("account","firebaseAuthWithGoogle:"+account.id)
firebaseAuthWithGoogle(account.idToken!!)
}catch (e : ApiException){
Log.i(ContentValues.TAG, "Google sign in failed", e)
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
signInButton.visibility= View.GONE
progressBar.visibility= View.VISIBLE
val credential= GoogleAuthProvider.getCredential(idToken,null)
GlobalScope.launch(Dispatchers.IO) {
val auth=auth.signInWithCredential(credential).await()
val firebaseUser=auth.user
Log.i("user",firebaseUser.toString())
withContext(Dispatchers.Main){
updateUI(firebaseUser)
}
}
}
private fun updateUI(firebaseUser: FirebaseUser?) {
if(firebaseUser != null)
{
val intent= Intent(this,MainActivity::class.java)
startActivity(intent)
Log.i("intent","Intent Started")
// Toast.makeText(applicationContext,"Sign In Successful",Toast.LENGTH_SHORT).show()
finish()
}
else{
signInButton.visibility= View.VISIBLE
progressBar.visibility=View.GONE
Toast.makeText(this,"Sign In failed", Toast.LENGTH_SHORT).show()
}
}
}
Here is the logcat ( I have highlighted the result code that I logged)
I am very new to android development and this my first time working with firebase

GetToken failed with status code: ServiceDisabled

I am using Google Sign in to login into a app I am building to display calendars. Post Google Sign in - it also logs into Firebase where the user data is stored in the Realtime Database. While the whole app was working properly - suddenly it stopped syncing with the Google Calendar API and I get the below "Errors" in the Info. I am able to login and with new accounts just no sync - app works - no data. I have tried checking multiple issues and even reverted to old code - no diff. Firebase user data is also being displayed in the app. Can anybody please suggest an approach to solving this issue?
2021-01-04 09:59:21.021 2139-4708/com.google.android.gms.persistent W/Auth: [GetToken] GetToken failed with status code: ServiceDisabled
2021-01-04 09:59:21.022 10175-10254/ W/System.err: com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAuthIOException
2021-01-04 09:59:21.022 10175-10254/ W/System.err: at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:286)
2021-01-04 09:59:21.022 10175-10254/ W/System.err: at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
2021-01-04 09:59:21.023 10175-10254/ W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
2021-01-04 09:59:21.023 10175-10254/ W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
2021-01-04 09:59:21.023 10175-10254/ W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
2021-01-04 09:59:21.023 10175-10254/ W/System.err: at .Fragments.Home$syncWholeCalendar$1.invokeSuspend(Home.kt:298)
Below is the code I use to get the user to sign in
private const val TAG = "WelcomeActivity"
class WelcomeActivity : AppCompatActivity() {
var firebaseUser: FirebaseUser? = null
//For Google Sign In
val RC_SIGN_IN: Int = 9001
private lateinit var mGoogleSignInClient: GoogleSignInClient
lateinit var mGoogleSignInOptions: GoogleSignInOptions
private lateinit var firebaseAuth: FirebaseAuth
private var firebaseUserID : String = ""
private lateinit var refUsers : DatabaseReference
//get data from google signin in handlesigninresult
private var googleId = ""
private var googleFirstName = ""
private var googleLastName = ""
private var googleEmail = ""
private var googleProfilePicURL = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_welcome)
// //For google sign in
// configureGoogleSignIn()
// setupUI()
firebaseAuth = FirebaseAuth.getInstance()
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("896894788293-oe0enptjj2hltdde9isemuf89gtkb7u4.apps.googleusercontent.com")
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, gso)
google_login.setOnClickListener {
signIn()
}
login_welcome.setOnClickListener {
val intent = Intent(this#WelcomeActivity, LoginActivity::class.java)
startActivity(intent)
finish()
}
}
private fun signIn() {
val signInIntent = mGoogleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task =
GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
}
}
private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
try {
val account = completedTask.getResult(
ApiException::class.java
)
// Signed in successfully
googleId = account?.id ?: ""
Log.i("Google ID", googleId)
googleFirstName = account?.givenName ?: ""
Log.i("Google First Name", googleFirstName)
googleLastName = account?.familyName ?: ""
Log.i("Google Last Name", googleLastName)
googleEmail = account?.email ?: ""
Log.i("Google Email", googleEmail)
val googleIdToken: String = account?.idToken ?: ""
Log.i("Google ID Token", googleIdToken)
googleProfilePicURL = account?.photoUrl.toString()
Log.i("Google Profile Pic URL", googleProfilePicURL)
firebaseAuthWithGoogle(googleIdToken)
} catch (e: ApiException) {
// Sign in was unsuccessful
Log.e(
"failed code=", e.statusCode.toString()
)
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
firebaseAuth.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")
firebaseUserID = firebaseAuth.currentUser!!.uid
refUsers = FirebaseDatabase.getInstance().reference.child("Users").child(
firebaseUserID
)
refUsers.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
if (p0.exists()) {
val user: Users? = p0.getValue(Users::class.java)
//Check if user exists in the database
if (user!!.getFirstName() != null) {
val intent = Intent(
this#WelcomeActivity,
IntroSplashScreen::class.java
)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
} else {
val usersHashMap = HashMap<String, Any>()
usersHashMap["uid"] = firebaseUserID
usersHashMap["firstname"] = googleFirstName
usersHashMap["surname"] = googleLastName
usersHashMap["profile"] = googleProfilePicURL
usersHashMap["primaryEmail"] = googleEmail
usersHashMap["search"] =
googleFirstName.toLowerCase(Locale.ROOT)
refUsers.updateChildren(usersHashMap)
.addOnCompleteListener {
if (task.isSuccessful) {
val intent = Intent(
this#WelcomeActivity,
IntroSplashScreen::class.java
)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
}
}
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
// ...
}
// ...
}
}
private fun refreshIdToken() {
// Attempt to silently refresh the GoogleSignInAccount. If the GoogleSignInAccount
// already has a valid token this method may complete immediately.
//
// 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 and get a valid
// ID token. Cross-device single sign on will occur in this branch.
mGoogleSignInClient.silentSignIn()
.addOnCompleteListener(
this
) { task -> handleSignInResult(task) }
}
override fun onStart() {
super.onStart()
//Checks if the Google IDToken has expired, if yes it refreshes by SilentSign in and generates new Firebase Token
refreshIdToken()
//Checks if user is logged in to firebase
firebaseUser = FirebaseAuth.getInstance().currentUser
//If logged in then sends to MainActivity
if(firebaseUser!=null){
startActivity(IntroSplashScreen.getLaunchIntent(this))
finish()
}
}
override fun onResume() {
super.onResume()
refreshIdToken()
}
}
Needed to create a Beta Test Program, as anybody who was not associated/listed was blocked from accessing data.

Login with google work from android studio but don't work from google play

I built an app with google login.
When I connect the device to the android studio the log in work perfect, But when I download my app from google play it fails to connect for some reason...
I tried to find a solution and I couldn't find one...
That's the code ... I would love if anyone has any idea what the problem is..
Thanks for your time!
class firstActivity : AppCompatActivity(){
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = FirebaseAuth.getInstance()
val acct = GoogleSignIn.getLastSignedInAccount(this)
if (acct != null) {
val personName = acct.displayName
val personGivenName = acct.givenName
val personFamilyName = acct.familyName
val personEmail = acct.email
val personId = acct.id
}
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_idd))
.requestEmail()
.build()
val mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signinButtonGoogle.setOnClickListener {
val signInIntent: Intent = mGoogleSignInClient.getSignInIntent()
startActivityForResult(signInIntent, Companion.RC_SIGN_IN)
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
GoogleSignInApi.getSignInIntent(...);
if (requestCode == Companion.RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)
firebaseAuthWithGoogle(account!!)
} catch (e: ApiException) {
Toast.makeText(applicationContext, "Google sign in failed", Toast.LENGTH_SHORT)
.show()
}
}
}
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
val progressDialog = ProgressDialog(this)
progressDialog.setMessage("Connecting...")
progressDialog.setCancelable(false)
progressDialog.show()
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = auth.currentUser
signinButtonGoogle.visibility = View.VISIBLE
Handler().postDelayed({ progressDialog.dismiss() }, 0)
val leagueIntent = Intent(this, homeActivity::class.java)
startActivity(leagueIntent)
} else {
Toast.makeText(applicationContext, "Authentication Failed.", Toast.LENGTH_SHORT).show()
signinButtonGoogle.visibility = View.VISIBLE
Handler().postDelayed({ progressDialog.dismiss() }, 0)
}
}
}
companion object {
const val RC_SIGN_IN = 123
}
}
because google play have another SH1 for relase , so you can find it like image and goto firbase manger for your prokect then add new one ,
image

Categories

Resources