我正在将 FirebaseAuth 集成到我正在构建的 Android 应用程序中。通过添加 SDK、下载和添加 google-services.json 文件,我已成功将 firebase 集成到应用程序中。
当我尝试注册新用户时出现问题。用户被添加到 firebase 控制台,但我无法检索登录用户来更新名称。这是我正在使用它的 fragment 中的代码。
requireActivity().let {
val user = authenticationService.signUpWithEmailAndPassword(email, password)
user?.let {
authenticationService.updateUser(it, name)
navigationService.openHomeScreen()//open next creen
}
}
authenticationService 中的注册函数
fun signUpWithEmailAndPassword(email: String, password: String): FirebaseUser? {
signOutCurrentUser()
firebaseAuth.createUserWithEmailAndPassword(email, password)
return firebaseAuth.currentUser
}
更新用户功能
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.")
}
}
}
退出当前用户功能
private fun signOutCurrentUser() {
firebaseAuth.currentUser?.let {
firebaseAuth.signOut()
}
}
问题是用户是 添加成功但是
firebaseAuth.currentUser
始终返回 null。我尝试过的事情:
请大哥帮忙
最佳答案
在 Firebase 中创建用户(与大多数涉及基于云的 API 的调用一样)是一种异步操作,可能需要一些时间才能完成。到您的 return firebaseAuth.currentUser
时代码运行,用户创建尚未完成。
如果您只是使用完成处理程序在单个 block 中运行代码,您会发现它工作正常:
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)
}
// ...
}
另见:
关于android - 无法在 kotlin 中获取 firebase 当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62054762/