FIrebase sign in and out options are not working

Viewed 41

Can someone explain to me why this simple code is not working properly? In the beginning I created an object with auth and currentUser

object FirebaseUtils {
    val auth: FirebaseAuth = FirebaseAuth.getInstance()
    val currentUser: FirebaseUser? = auth.currentUser

}

My login activity function

 fun login(){
    val email = binding.loginInput.text.toString()
    val password = binding.passwordInput.text.toString()
    auth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener {
            task ->
            if (task.isSuccessful){
                task.result
                Log.d("login_status", "Logged: ${currentUser?.uid}")
                startActivity(Intent(this, MainActivity::class.java))
                finish()
            } else {
                Log.d("login_status", task.exception.toString())
            }
        }
}

Start activity:

lifecycleScope.launch {
        delay(2000)
        if(currentUser?.uid != null){
            Log.d("login_status", "Logged: ${currentUser.uid}")
            startActivity(Intent(applicationContext, MainActivity::class.java))
        }else{
            startActivity(Intent(applicationContext, LoginMainActivity::class.java))
        }
        finish()
    }

And sign out

 fun signOut(){
    auth.signOut()
    startActivity(Intent(this, LoginMainActivity::class.java))
    Log.d("login_status", "Signed out: ${currentUser?.uid}")
    finish()

}

The problem is that after the first login I can see that logged user is null so my app is crashing (no data for the user). However, after restarting I am logged in as this user. I cant also sign out - activity changes to the login screen but even if I pass different credentials the user remains the same.

EDIT When I log in and restart the app it works - the correct user is logged. When I log out and restart the app it also works - the user is signed out. So why is there a problem between activities

1 Answers

Your result is null because you are getting the result object out of the task object but you aren't doing anything with it. Simply calling:

task.result

Doesn't provide any benefit. However, you can save that result into a variable and call AuthResult#getUser() like this:

val user = task.result.getUser()
Log.d("login_status", "Logged: ${user?.uid}")

So right after you authenticate the user successfully, you'll be able to log the UID correctly.

Related