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
Related
I am trying to give user an option to login with google account using firebase
earlier i was successfully able to this this but recently i got this issue which i am not sure that why it is happening
ISSUE-> when i start another activity and get result back in registerForActivityResult()
i always getting result.resultCode as 0 i.e RESULT_CANCELED
here is the signup fragment
class NewAccountFragment : Fragment() {
private lateinit var binding: FragmentNewAccountBinding
//declaring and initializing the shareViewModel
private val sharedViewModel:SharedViewModel by activityViewModels()
private lateinit var auth:FirebaseAuth
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View{
val view = FragmentNewAccountBinding.inflate(inflater,container,false)
binding = view
return view.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//setting the things to use if user taps on google button
sharedViewModel.getGso(requireContext()) //to get info from user's gmail id
sharedViewModel.getGSC(requireContext())//google signInClient
//initializing fire base auth
auth = FirebaseAuth.getInstance()
//handling the click of register button
binding.registerButton.setOnClickListener {
startRegistrationProcess()
}
//handling the click of google sign in button
binding.googleSignInButton.setOnClickListener {
val intent = sharedViewModel.getSignInIntent(requireContext())
if(intent!=null){
//receiving intent to show pop up on screen to show option which account he/she will use for this app
//and passing this intent to googleLauncher
googleLauncher.launch(intent)
}
}
}
//this will handle the result from that pop up
private var googleLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
when (result.resultCode) {
RESULT_OK-> {
// There are no request codes
val data: Intent? = result.data
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
//telling sharedViewModel to signIn the user with it's google account on firebase
sharedViewModel.firebaseAuthWithGoogle(account.idToken!!, requireContext())
//clearing up the inputs
binding.passwordEt.setText("")
binding.emailEt.setText("")
} catch (e: ApiException) {
// Google Sign In failed, show error on toast
Toast.makeText(requireContext(), e.message, Toast.LENGTH_SHORT).show()
}
}
RESULT_CANCELED->{
Toast.makeText(requireContext(),"result failed",Toast.LENGTH_SHORT).show()
}
}
}
private fun startRegistrationProcess() {
//getting text from editTexts
val email = binding.emailEt.text.toString().trim()
val password = binding.passwordEt.text.toString().trim()
//Validation.
//if email matches the standards
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.emailEt.error = "Invalid Email"
} else if (password.length < 8) {
//set error and focus on passWord.
binding.passwordEt.error = "Enter more than 7 character"
} else {
//telling shareViewModel to crate account for this use with email and password
sharedViewModel.registerOnFirebase(email,password,requireContext())
binding.passwordEt.setText("")
binding.emailEt.setText("")
}
}
}
and here is the viewModel attached to it
class SharedViewModel:ViewModel() {
private lateinit var gso:GoogleSignInOptions
private lateinit var googleSignInClient:GoogleSignInClient
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
// -> FOR NEW ACCOUNT FRAGMENT
//for firebase registration
fun registerOnFirebase( email:String, password:String,context: Context){
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { task->
if(task.isSuccessful){
//user has signed in successfully
Toast.makeText(context, "Account created successfully!!", Toast.LENGTH_SHORT).show()
// go to dashboard activity
val intent = Intent(context,DashboardActivity::class.java)
//intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
context.startActivity(intent)
MainActivity.isAlive.value = false
}else{
Toast.makeText(context, "error: ${task.exception!!.message}", Toast.LENGTH_SHORT).show()
}
}
}
//for google registration
fun getGso(context: Context){
gso = GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(context.getString(R.string.server_client_id))
.requestEmail()
.build()
}
fun getGSC(context: Context){
googleSignInClient = GoogleSignIn.getClient(context,gso)
}
fun getSignInIntent(context: Context): Intent? {
val duplicate = checkDelicacy(context) //true if duplicate
if(duplicate){
Toast.makeText(context, "Already a member, Please logIn", Toast.LENGTH_SHORT).show()
} else {
return googleSignInClient.signInIntent
}
return null
}
fun firebaseAuthWithGoogle(idToken: String,context: Context) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential).addOnCompleteListener { task->
if(task.isSuccessful){
//if registered with google successfully then navigate to DashboardActivity with a toast
Toast.makeText(context, "Signed in with google", Toast.LENGTH_SHORT).show()
//navigate to DashboardActivity
val intent = Intent(context,DashboardActivity::class.java)
context.startActivity(intent)
MainActivity.isAlive.value = false
}else{
Toast.makeText(context, "error: ${task.exception!!.message}", Toast.LENGTH_SHORT).show()
}
}
}
private fun checkDelicacy(context: Context): Boolean {
val account = GoogleSignIn.getLastSignedInAccount(context)
return account!=null
}
// -> FOR ALREADY ACCOUNT FRAGMENT
//logging in with email and password
fun logInWithFireBase(email: String, password: String,context: Context) {
auth.signInWithEmailAndPassword(email,password).addOnCompleteListener { task->
if(task.isSuccessful){
//if logged in successfully then navigate to DashboardActivity with a toast
Toast.makeText(context, "Logged in successfully!!", Toast.LENGTH_SHORT).show()
val intent = Intent(context,DashboardActivity::class.java)
context.startActivity(intent)
MainActivity.isAlive.value = false
}else{
Toast.makeText(context, "error: ${task.exception!!.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
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.
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
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.
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