Unable to get firebase current user in kotlin

时光总嘲笑我的痴心妄想 提交于 2021-01-28 07:50:43

问题


I am integrating FirebaseAuth into an Android app that I am building. I have successfully integrated firebase into the app by adding the SDK, downloading and adding the google-services.json file.

The problem occurs when I try to Sign Up a new user. The user gets added to firebase console but I cannot retrieve the signed in user to update the name. This is the code from the fragment I am using it in.

requireActivity().let {
    val user = authenticationService.signUpWithEmailAndPassword(email, password)

    user?.let {
            authenticationService.updateUser(it, name)
            navigationService.openHomeScreen()//open next creen
    }
}

the signup function in the authenticationService

fun signUpWithEmailAndPassword(email: String, password: String): FirebaseUser? {
    signOutCurrentUser()
     firebaseAuth.createUserWithEmailAndPassword(email, password)
    return firebaseAuth.currentUser
}

the update user function

fun updateUser(user: FirebaseUser?, name: String) {
    val profileUpdates = UserProfileChangeRequest.Builder().apply {
        displayName = name
    }.build()
    user?.updateProfile(profileUpdates)?.addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Timber.d("User profile updated.")
        }
    }
}

the sign out current user function

private fun signOutCurrentUser() {
    firebaseAuth.currentUser?.let {
        firebaseAuth.signOut()
    }
}

The issue is that user is Added successfully but firebaseAuth.currentUser returns null always.

Things I have tried:

  • Adding authStateListener
  • Adding onSuccessListener
  • Adding onCompleteListener

Please help a brother out


回答1:


Creating a user in Firebase is (like most calls involving cloud-based APIs) an asynchronous operation, which may take time to complete. By the time your return firebaseAuth.currentUser code runs, the user creation has not been completed yet.

If you simply the code to run in a single block, with a completion handler, you'll see that it works fine:

firebaseAuth.createUserWithEmailAndPassword(email, password)
  .addOnCompleteListener(this) { task ->
    if (task.isSuccessful) {
        val user = auth.currentUser

        val profileUpdates = UserProfileChangeRequest.Builder().apply {
            displayName = name
        }.build()
        user?.updateProfile(profileUpdates)?.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Timber.d("User profile updated.")
            }
        }
    } else {
        // If sign in fails, display a message to the user.
        Log.w(TAG, "createUserWithEmail:failure", task.exception)
        Toast.makeText(baseContext, "Authentication failed.",
                Toast.LENGTH_SHORT).show()
        updateUI(null)
    }

    // ...
  }

Also see:

  • getContactsFromFirebase() method return an empty list
  • Firebase retrieve data Null outside method
  • Retrieve String out of addValueEventListener Firebase
  • Setting Singleton property value in Firebase Listener (which shows using semaphores to make the code block, but which didn't work on Android when I last tried it).


来源:https://stackoverflow.com/questions/62054762/unable-to-get-firebase-current-user-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!