FirebaseAuth.currentUser is null where as GoogleSignIn.getLastSignedInAccount(this)
FirebaseAuth.currentUser
is null where asGoogleSignIn.getLastSignedInAccount(this)
in onStart I fetched last SignedIn Account it give me the last login but when I call FirebaseAuth.currentUser it is null why..
GoogleSignInActivity.kt
class GoogleSignInActivity : BaseActivity(), View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private val RC_SIGN_IN = 9001
private var mGoogleApiClient: GoogleApiClient? = null
private var mGoogleSignInClient: GoogleSignInClient? = null
// Firebase instance variables
private val mFirebaseAuth: FirebaseAuth? = FirebaseAuth.getInstance()
private var mAuthListener: FirebaseAuth.AuthStateListener? = null
private fun configureSignIn() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id)) //it is option I think
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mGoogleApiClient = GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build()
mGoogleApiClient?.connect();
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_google_sign_in)
val mSignInButton = findViewById(R.id.sign_in_button) as SignInButton
mSignInButton.setSize(SignInButton.SIZE_STANDARD)
mSignInButton.setOnClickListener(this)
configureSignIn()
mAuthListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
// Get signedIn user
val user = firebaseAuth.currentUser
//if user is signed in, we call a helper method to save the user details to Firebase
if (user != null) {
// User is signed in
createUserInFirebaseHelper(user) // may be I don't require it here...
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.uid)
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out")
}
}
}
override fun onStart() {
super.onStart()
/* val account = GoogleSignIn.getLastSignedInAccount(this)
updateUI(account)*/ // 1st approach...
var firebaseUser = mFirebaseAuth?.currentUser
updateUI(firebaseUser)
/*if (mAuthListener != null){ // fixme commented so it is not sign out..
FirebaseAuth.getInstance().signOut();
}*/
mFirebaseAuth?.addAuthStateListener(mAuthListener!!);
}
private fun createUserInFirebaseHelper(firebaseuser: FirebaseUser?) {
//fixme https://github.com/Ginowine/android-firebase-authentication/blob/master/app/src/main/java/com/tutorial/authentication/MainActivity.java
val userRef = db.collection("userCollection").document(firebaseuser!!.uid).set(
UserBO(firebaseuser.uid, firebaseuser.displayName!!, firebaseuser.email!!))
userRef.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this@GoogleSignInActivity, "Login successful & User Added",
Toast.LENGTH_SHORT).show()
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
} else {
Toast.makeText(this@GoogleSignInActivity, "failed", Toast.LENGTH_LONG).show()
}
}
}
override fun onStop() {
super.onStop()
if (mAuthListener != null) {
mFirebaseAuth?.removeAuthStateListener(mAuthListener!!);
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)
if (account != null)
firebaseAuthWithGoogle(account)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
// ...
}
// The Task returned from this call is always completed, no need to attach
// a listener.
/*val task = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)*/
//third approach..
/*val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
if(result.isSuccess){
val googleAccount = result.getSignInAccount();
val idToken = googleAccount?.getIdToken() //getName ,getPhoto,email etc..
//save user is logged IN in sharedPref
val credential = GoogleAuthProvider.getCredential(idToken, null)
firebaseAuthWithGoogle(credential)
}*/
} else {
Toast.makeText(this, "Login Unsuccessful", Toast.LENGTH_LONG).show()
}
}
/*private fun updateUI(userInfo: GoogleSignInAccount?) {
// if it is null then display the UI for sign in button
//hide this activity and move to main Screen.
if (userInfo != null) {
if(!userInfo.email!!.isEmpty()){
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
}
*//*val personName = userInfo.getDisplayName()
val personGivenName = userInfo.getGivenName()
val personFamilyName = userInfo.getFamilyName()
val personEmail = userInfo.getEmail()
val personId = userInfo.getId()
val personPhoto = userInfo.getPhotoUrl()*//*
}
}*/
private fun updateUI(userInfo: FirebaseUser?) {
// if it is null then display the UI for sign in button
//hide this activity and move to main Screen.
if (userInfo != null) {
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
/*val personName = userInfo.getDisplayName()
val personGivenName = userInfo.getGivenName()
val personFamilyName = userInfo.getFamilyName()
val personEmail = userInfo.getEmail()
val personId = userInfo.getId()
val personPhoto = userInfo.getPhotoUrl()*/
}
else{
}
}
override fun onClick(v: View?) {
when (v?.getId()) {
R.id.sign_in_button -> signIn()
}
/*when(v?.id){
R.id.sign_in_button
}*/
}
private fun signIn() {
val signInIntent = mGoogleSignInClient?.getSignInIntent() ///Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient)
startActivityForResult(signInIntent, RC_SIGN_IN)
}
/*private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>?) {
try {
val account = completedTask?.getResult(ApiException::class.java)
// Signed in successfully, show authenticated UI.
updateUI(account)
} catch (e: ApiException) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.statusCode)
updateUI(null)
}
}*/
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.id!!)
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
mFirebaseAuth?.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")
createUserInFirebaseHelper(mFirebaseAuth?.currentUser)
/*val user = mFirebaseAuth?.currentUser
if (user != null)
updateUI(user)*/
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
///Snackbar.make(main_layout, "Authentication Failed.", Snackbar.LENGTH_SHORT).show()
updateUI(null)
}
// ...
}
}
/*private fun firebaseAuthWithGoogle(credential: AuthCredential) {
//showProgressDialog();
mFirebaseAuth?.signInWithCredential(credential)?.addOnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "signInWithCredential" + task.exception!!.message)
task.exception!!.printStackTrace()
Toast.makeText(this@GoogleSignInActivity, "Authentication failed.",
Toast.LENGTH_SHORT).show()
} else {
createUserInFirebaseHelper(mFirebaseAuth.getCurrentUser())
}
}
}*/
override fun onConnected(bundle: Bundle?) {
Toast.makeText(this@GoogleSignInActivity, "Api Connected", Toast.LENGTH_LONG).show()
}
override fun onConnectionSuspended(p0: Int) {
}
override fun onConnectionFailed(p0: ConnectionResult) {
Toast.makeText(this@GoogleSignInActivity, "Api Failed to connect", Toast.LENGTH_LONG).show()
}
}
What am i doing wrong??
Edit Now it's working
android kotlin firebase-authentication google-signin
add a comment |
FirebaseAuth.currentUser
is null where asGoogleSignIn.getLastSignedInAccount(this)
in onStart I fetched last SignedIn Account it give me the last login but when I call FirebaseAuth.currentUser it is null why..
GoogleSignInActivity.kt
class GoogleSignInActivity : BaseActivity(), View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private val RC_SIGN_IN = 9001
private var mGoogleApiClient: GoogleApiClient? = null
private var mGoogleSignInClient: GoogleSignInClient? = null
// Firebase instance variables
private val mFirebaseAuth: FirebaseAuth? = FirebaseAuth.getInstance()
private var mAuthListener: FirebaseAuth.AuthStateListener? = null
private fun configureSignIn() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id)) //it is option I think
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mGoogleApiClient = GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build()
mGoogleApiClient?.connect();
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_google_sign_in)
val mSignInButton = findViewById(R.id.sign_in_button) as SignInButton
mSignInButton.setSize(SignInButton.SIZE_STANDARD)
mSignInButton.setOnClickListener(this)
configureSignIn()
mAuthListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
// Get signedIn user
val user = firebaseAuth.currentUser
//if user is signed in, we call a helper method to save the user details to Firebase
if (user != null) {
// User is signed in
createUserInFirebaseHelper(user) // may be I don't require it here...
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.uid)
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out")
}
}
}
override fun onStart() {
super.onStart()
/* val account = GoogleSignIn.getLastSignedInAccount(this)
updateUI(account)*/ // 1st approach...
var firebaseUser = mFirebaseAuth?.currentUser
updateUI(firebaseUser)
/*if (mAuthListener != null){ // fixme commented so it is not sign out..
FirebaseAuth.getInstance().signOut();
}*/
mFirebaseAuth?.addAuthStateListener(mAuthListener!!);
}
private fun createUserInFirebaseHelper(firebaseuser: FirebaseUser?) {
//fixme https://github.com/Ginowine/android-firebase-authentication/blob/master/app/src/main/java/com/tutorial/authentication/MainActivity.java
val userRef = db.collection("userCollection").document(firebaseuser!!.uid).set(
UserBO(firebaseuser.uid, firebaseuser.displayName!!, firebaseuser.email!!))
userRef.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this@GoogleSignInActivity, "Login successful & User Added",
Toast.LENGTH_SHORT).show()
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
} else {
Toast.makeText(this@GoogleSignInActivity, "failed", Toast.LENGTH_LONG).show()
}
}
}
override fun onStop() {
super.onStop()
if (mAuthListener != null) {
mFirebaseAuth?.removeAuthStateListener(mAuthListener!!);
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)
if (account != null)
firebaseAuthWithGoogle(account)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
// ...
}
// The Task returned from this call is always completed, no need to attach
// a listener.
/*val task = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)*/
//third approach..
/*val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
if(result.isSuccess){
val googleAccount = result.getSignInAccount();
val idToken = googleAccount?.getIdToken() //getName ,getPhoto,email etc..
//save user is logged IN in sharedPref
val credential = GoogleAuthProvider.getCredential(idToken, null)
firebaseAuthWithGoogle(credential)
}*/
} else {
Toast.makeText(this, "Login Unsuccessful", Toast.LENGTH_LONG).show()
}
}
/*private fun updateUI(userInfo: GoogleSignInAccount?) {
// if it is null then display the UI for sign in button
//hide this activity and move to main Screen.
if (userInfo != null) {
if(!userInfo.email!!.isEmpty()){
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
}
*//*val personName = userInfo.getDisplayName()
val personGivenName = userInfo.getGivenName()
val personFamilyName = userInfo.getFamilyName()
val personEmail = userInfo.getEmail()
val personId = userInfo.getId()
val personPhoto = userInfo.getPhotoUrl()*//*
}
}*/
private fun updateUI(userInfo: FirebaseUser?) {
// if it is null then display the UI for sign in button
//hide this activity and move to main Screen.
if (userInfo != null) {
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
/*val personName = userInfo.getDisplayName()
val personGivenName = userInfo.getGivenName()
val personFamilyName = userInfo.getFamilyName()
val personEmail = userInfo.getEmail()
val personId = userInfo.getId()
val personPhoto = userInfo.getPhotoUrl()*/
}
else{
}
}
override fun onClick(v: View?) {
when (v?.getId()) {
R.id.sign_in_button -> signIn()
}
/*when(v?.id){
R.id.sign_in_button
}*/
}
private fun signIn() {
val signInIntent = mGoogleSignInClient?.getSignInIntent() ///Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient)
startActivityForResult(signInIntent, RC_SIGN_IN)
}
/*private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>?) {
try {
val account = completedTask?.getResult(ApiException::class.java)
// Signed in successfully, show authenticated UI.
updateUI(account)
} catch (e: ApiException) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.statusCode)
updateUI(null)
}
}*/
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.id!!)
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
mFirebaseAuth?.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")
createUserInFirebaseHelper(mFirebaseAuth?.currentUser)
/*val user = mFirebaseAuth?.currentUser
if (user != null)
updateUI(user)*/
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
///Snackbar.make(main_layout, "Authentication Failed.", Snackbar.LENGTH_SHORT).show()
updateUI(null)
}
// ...
}
}
/*private fun firebaseAuthWithGoogle(credential: AuthCredential) {
//showProgressDialog();
mFirebaseAuth?.signInWithCredential(credential)?.addOnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "signInWithCredential" + task.exception!!.message)
task.exception!!.printStackTrace()
Toast.makeText(this@GoogleSignInActivity, "Authentication failed.",
Toast.LENGTH_SHORT).show()
} else {
createUserInFirebaseHelper(mFirebaseAuth.getCurrentUser())
}
}
}*/
override fun onConnected(bundle: Bundle?) {
Toast.makeText(this@GoogleSignInActivity, "Api Connected", Toast.LENGTH_LONG).show()
}
override fun onConnectionSuspended(p0: Int) {
}
override fun onConnectionFailed(p0: ConnectionResult) {
Toast.makeText(this@GoogleSignInActivity, "Api Failed to connect", Toast.LENGTH_LONG).show()
}
}
What am i doing wrong??
Edit Now it's working
android kotlin firebase-authentication google-signin
There's a lot of code here, and it's hard to read it and point out a mistake. When you run this code, it's the call tomFirebaseAuth?.signInWithCredential(credential)
that will sign the user in to Firebase with their established Google auth credentials. Did you run this code in a debugger to see if it ends up at that line?
– Frank van Puffelen
Nov 23 '18 at 14:41
add a comment |
FirebaseAuth.currentUser
is null where asGoogleSignIn.getLastSignedInAccount(this)
in onStart I fetched last SignedIn Account it give me the last login but when I call FirebaseAuth.currentUser it is null why..
GoogleSignInActivity.kt
class GoogleSignInActivity : BaseActivity(), View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private val RC_SIGN_IN = 9001
private var mGoogleApiClient: GoogleApiClient? = null
private var mGoogleSignInClient: GoogleSignInClient? = null
// Firebase instance variables
private val mFirebaseAuth: FirebaseAuth? = FirebaseAuth.getInstance()
private var mAuthListener: FirebaseAuth.AuthStateListener? = null
private fun configureSignIn() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id)) //it is option I think
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mGoogleApiClient = GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build()
mGoogleApiClient?.connect();
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_google_sign_in)
val mSignInButton = findViewById(R.id.sign_in_button) as SignInButton
mSignInButton.setSize(SignInButton.SIZE_STANDARD)
mSignInButton.setOnClickListener(this)
configureSignIn()
mAuthListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
// Get signedIn user
val user = firebaseAuth.currentUser
//if user is signed in, we call a helper method to save the user details to Firebase
if (user != null) {
// User is signed in
createUserInFirebaseHelper(user) // may be I don't require it here...
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.uid)
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out")
}
}
}
override fun onStart() {
super.onStart()
/* val account = GoogleSignIn.getLastSignedInAccount(this)
updateUI(account)*/ // 1st approach...
var firebaseUser = mFirebaseAuth?.currentUser
updateUI(firebaseUser)
/*if (mAuthListener != null){ // fixme commented so it is not sign out..
FirebaseAuth.getInstance().signOut();
}*/
mFirebaseAuth?.addAuthStateListener(mAuthListener!!);
}
private fun createUserInFirebaseHelper(firebaseuser: FirebaseUser?) {
//fixme https://github.com/Ginowine/android-firebase-authentication/blob/master/app/src/main/java/com/tutorial/authentication/MainActivity.java
val userRef = db.collection("userCollection").document(firebaseuser!!.uid).set(
UserBO(firebaseuser.uid, firebaseuser.displayName!!, firebaseuser.email!!))
userRef.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this@GoogleSignInActivity, "Login successful & User Added",
Toast.LENGTH_SHORT).show()
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
} else {
Toast.makeText(this@GoogleSignInActivity, "failed", Toast.LENGTH_LONG).show()
}
}
}
override fun onStop() {
super.onStop()
if (mAuthListener != null) {
mFirebaseAuth?.removeAuthStateListener(mAuthListener!!);
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)
if (account != null)
firebaseAuthWithGoogle(account)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
// ...
}
// The Task returned from this call is always completed, no need to attach
// a listener.
/*val task = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)*/
//third approach..
/*val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
if(result.isSuccess){
val googleAccount = result.getSignInAccount();
val idToken = googleAccount?.getIdToken() //getName ,getPhoto,email etc..
//save user is logged IN in sharedPref
val credential = GoogleAuthProvider.getCredential(idToken, null)
firebaseAuthWithGoogle(credential)
}*/
} else {
Toast.makeText(this, "Login Unsuccessful", Toast.LENGTH_LONG).show()
}
}
/*private fun updateUI(userInfo: GoogleSignInAccount?) {
// if it is null then display the UI for sign in button
//hide this activity and move to main Screen.
if (userInfo != null) {
if(!userInfo.email!!.isEmpty()){
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
}
*//*val personName = userInfo.getDisplayName()
val personGivenName = userInfo.getGivenName()
val personFamilyName = userInfo.getFamilyName()
val personEmail = userInfo.getEmail()
val personId = userInfo.getId()
val personPhoto = userInfo.getPhotoUrl()*//*
}
}*/
private fun updateUI(userInfo: FirebaseUser?) {
// if it is null then display the UI for sign in button
//hide this activity and move to main Screen.
if (userInfo != null) {
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
/*val personName = userInfo.getDisplayName()
val personGivenName = userInfo.getGivenName()
val personFamilyName = userInfo.getFamilyName()
val personEmail = userInfo.getEmail()
val personId = userInfo.getId()
val personPhoto = userInfo.getPhotoUrl()*/
}
else{
}
}
override fun onClick(v: View?) {
when (v?.getId()) {
R.id.sign_in_button -> signIn()
}
/*when(v?.id){
R.id.sign_in_button
}*/
}
private fun signIn() {
val signInIntent = mGoogleSignInClient?.getSignInIntent() ///Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient)
startActivityForResult(signInIntent, RC_SIGN_IN)
}
/*private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>?) {
try {
val account = completedTask?.getResult(ApiException::class.java)
// Signed in successfully, show authenticated UI.
updateUI(account)
} catch (e: ApiException) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.statusCode)
updateUI(null)
}
}*/
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.id!!)
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
mFirebaseAuth?.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")
createUserInFirebaseHelper(mFirebaseAuth?.currentUser)
/*val user = mFirebaseAuth?.currentUser
if (user != null)
updateUI(user)*/
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
///Snackbar.make(main_layout, "Authentication Failed.", Snackbar.LENGTH_SHORT).show()
updateUI(null)
}
// ...
}
}
/*private fun firebaseAuthWithGoogle(credential: AuthCredential) {
//showProgressDialog();
mFirebaseAuth?.signInWithCredential(credential)?.addOnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "signInWithCredential" + task.exception!!.message)
task.exception!!.printStackTrace()
Toast.makeText(this@GoogleSignInActivity, "Authentication failed.",
Toast.LENGTH_SHORT).show()
} else {
createUserInFirebaseHelper(mFirebaseAuth.getCurrentUser())
}
}
}*/
override fun onConnected(bundle: Bundle?) {
Toast.makeText(this@GoogleSignInActivity, "Api Connected", Toast.LENGTH_LONG).show()
}
override fun onConnectionSuspended(p0: Int) {
}
override fun onConnectionFailed(p0: ConnectionResult) {
Toast.makeText(this@GoogleSignInActivity, "Api Failed to connect", Toast.LENGTH_LONG).show()
}
}
What am i doing wrong??
Edit Now it's working
android kotlin firebase-authentication google-signin
FirebaseAuth.currentUser
is null where asGoogleSignIn.getLastSignedInAccount(this)
in onStart I fetched last SignedIn Account it give me the last login but when I call FirebaseAuth.currentUser it is null why..
GoogleSignInActivity.kt
class GoogleSignInActivity : BaseActivity(), View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private val RC_SIGN_IN = 9001
private var mGoogleApiClient: GoogleApiClient? = null
private var mGoogleSignInClient: GoogleSignInClient? = null
// Firebase instance variables
private val mFirebaseAuth: FirebaseAuth? = FirebaseAuth.getInstance()
private var mAuthListener: FirebaseAuth.AuthStateListener? = null
private fun configureSignIn() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id)) //it is option I think
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mGoogleApiClient = GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build()
mGoogleApiClient?.connect();
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_google_sign_in)
val mSignInButton = findViewById(R.id.sign_in_button) as SignInButton
mSignInButton.setSize(SignInButton.SIZE_STANDARD)
mSignInButton.setOnClickListener(this)
configureSignIn()
mAuthListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
// Get signedIn user
val user = firebaseAuth.currentUser
//if user is signed in, we call a helper method to save the user details to Firebase
if (user != null) {
// User is signed in
createUserInFirebaseHelper(user) // may be I don't require it here...
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.uid)
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out")
}
}
}
override fun onStart() {
super.onStart()
/* val account = GoogleSignIn.getLastSignedInAccount(this)
updateUI(account)*/ // 1st approach...
var firebaseUser = mFirebaseAuth?.currentUser
updateUI(firebaseUser)
/*if (mAuthListener != null){ // fixme commented so it is not sign out..
FirebaseAuth.getInstance().signOut();
}*/
mFirebaseAuth?.addAuthStateListener(mAuthListener!!);
}
private fun createUserInFirebaseHelper(firebaseuser: FirebaseUser?) {
//fixme https://github.com/Ginowine/android-firebase-authentication/blob/master/app/src/main/java/com/tutorial/authentication/MainActivity.java
val userRef = db.collection("userCollection").document(firebaseuser!!.uid).set(
UserBO(firebaseuser.uid, firebaseuser.displayName!!, firebaseuser.email!!))
userRef.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this@GoogleSignInActivity, "Login successful & User Added",
Toast.LENGTH_SHORT).show()
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
} else {
Toast.makeText(this@GoogleSignInActivity, "failed", Toast.LENGTH_LONG).show()
}
}
}
override fun onStop() {
super.onStop()
if (mAuthListener != null) {
mFirebaseAuth?.removeAuthStateListener(mAuthListener!!);
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)
if (account != null)
firebaseAuthWithGoogle(account)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
// ...
}
// The Task returned from this call is always completed, no need to attach
// a listener.
/*val task = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)*/
//third approach..
/*val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
if(result.isSuccess){
val googleAccount = result.getSignInAccount();
val idToken = googleAccount?.getIdToken() //getName ,getPhoto,email etc..
//save user is logged IN in sharedPref
val credential = GoogleAuthProvider.getCredential(idToken, null)
firebaseAuthWithGoogle(credential)
}*/
} else {
Toast.makeText(this, "Login Unsuccessful", Toast.LENGTH_LONG).show()
}
}
/*private fun updateUI(userInfo: GoogleSignInAccount?) {
// if it is null then display the UI for sign in button
//hide this activity and move to main Screen.
if (userInfo != null) {
if(!userInfo.email!!.isEmpty()){
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
}
*//*val personName = userInfo.getDisplayName()
val personGivenName = userInfo.getGivenName()
val personFamilyName = userInfo.getFamilyName()
val personEmail = userInfo.getEmail()
val personId = userInfo.getId()
val personPhoto = userInfo.getPhotoUrl()*//*
}
}*/
private fun updateUI(userInfo: FirebaseUser?) {
// if it is null then display the UI for sign in button
//hide this activity and move to main Screen.
if (userInfo != null) {
val intent = Intent(this@GoogleSignInActivity, QuestionListActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
/*val personName = userInfo.getDisplayName()
val personGivenName = userInfo.getGivenName()
val personFamilyName = userInfo.getFamilyName()
val personEmail = userInfo.getEmail()
val personId = userInfo.getId()
val personPhoto = userInfo.getPhotoUrl()*/
}
else{
}
}
override fun onClick(v: View?) {
when (v?.getId()) {
R.id.sign_in_button -> signIn()
}
/*when(v?.id){
R.id.sign_in_button
}*/
}
private fun signIn() {
val signInIntent = mGoogleSignInClient?.getSignInIntent() ///Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient)
startActivityForResult(signInIntent, RC_SIGN_IN)
}
/*private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>?) {
try {
val account = completedTask?.getResult(ApiException::class.java)
// Signed in successfully, show authenticated UI.
updateUI(account)
} catch (e: ApiException) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.statusCode)
updateUI(null)
}
}*/
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.id!!)
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
mFirebaseAuth?.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")
createUserInFirebaseHelper(mFirebaseAuth?.currentUser)
/*val user = mFirebaseAuth?.currentUser
if (user != null)
updateUI(user)*/
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
///Snackbar.make(main_layout, "Authentication Failed.", Snackbar.LENGTH_SHORT).show()
updateUI(null)
}
// ...
}
}
/*private fun firebaseAuthWithGoogle(credential: AuthCredential) {
//showProgressDialog();
mFirebaseAuth?.signInWithCredential(credential)?.addOnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "signInWithCredential" + task.exception!!.message)
task.exception!!.printStackTrace()
Toast.makeText(this@GoogleSignInActivity, "Authentication failed.",
Toast.LENGTH_SHORT).show()
} else {
createUserInFirebaseHelper(mFirebaseAuth.getCurrentUser())
}
}
}*/
override fun onConnected(bundle: Bundle?) {
Toast.makeText(this@GoogleSignInActivity, "Api Connected", Toast.LENGTH_LONG).show()
}
override fun onConnectionSuspended(p0: Int) {
}
override fun onConnectionFailed(p0: ConnectionResult) {
Toast.makeText(this@GoogleSignInActivity, "Api Failed to connect", Toast.LENGTH_LONG).show()
}
}
What am i doing wrong??
Edit Now it's working
android kotlin firebase-authentication google-signin
android kotlin firebase-authentication google-signin
edited Nov 27 '18 at 5:34
Xar E Ahmer
asked Nov 23 '18 at 12:52
Xar E AhmerXar E Ahmer
22.3k8150206
22.3k8150206
There's a lot of code here, and it's hard to read it and point out a mistake. When you run this code, it's the call tomFirebaseAuth?.signInWithCredential(credential)
that will sign the user in to Firebase with their established Google auth credentials. Did you run this code in a debugger to see if it ends up at that line?
– Frank van Puffelen
Nov 23 '18 at 14:41
add a comment |
There's a lot of code here, and it's hard to read it and point out a mistake. When you run this code, it's the call tomFirebaseAuth?.signInWithCredential(credential)
that will sign the user in to Firebase with their established Google auth credentials. Did you run this code in a debugger to see if it ends up at that line?
– Frank van Puffelen
Nov 23 '18 at 14:41
There's a lot of code here, and it's hard to read it and point out a mistake. When you run this code, it's the call to
mFirebaseAuth?.signInWithCredential(credential)
that will sign the user in to Firebase with their established Google auth credentials. Did you run this code in a debugger to see if it ends up at that line?– Frank van Puffelen
Nov 23 '18 at 14:41
There's a lot of code here, and it's hard to read it and point out a mistake. When you run this code, it's the call to
mFirebaseAuth?.signInWithCredential(credential)
that will sign the user in to Firebase with their established Google auth credentials. Did you run this code in a debugger to see if it ends up at that line?– Frank van Puffelen
Nov 23 '18 at 14:41
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447095%2ffirebaseauth-currentuser-is-null-where-as-googlesignin-getlastsignedinaccountth%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447095%2ffirebaseauth-currentuser-is-null-where-as-googlesignin-getlastsignedinaccountth%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
There's a lot of code here, and it's hard to read it and point out a mistake. When you run this code, it's the call to
mFirebaseAuth?.signInWithCredential(credential)
that will sign the user in to Firebase with their established Google auth credentials. Did you run this code in a debugger to see if it ends up at that line?– Frank van Puffelen
Nov 23 '18 at 14:41