我想知道为什么不调用onCompleteListener而是将数据成功保存到FireBaseDatabase的原因。 我只想说:如果将数据保存到FireBaseDatabase,则将isSuccedded设置为true,但这不会发生。 isSucceeded始终为false。
val isSaved = SaveUserToDatabase(username)
if (isSaved) {
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show()
val intent = Intent(this, LatestTransactions::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.putExtra(CURRENT_USER, mAuth.currentUser.toString())
startActivity(intent)
} else {
register_tv_error.text = "Couldn't save user"
}
和功能:
private fun SaveUserToDatabase(username: String): Boolean {
val uid = mAuth.uid
var isSucceeded = false
val user = User(uid!!, username)
myRef = database.getReference("/users/$uid")
myRef.setValue(user).addOnCompleteListener{
if(it.isSuccessful){
isSucceeded = true
}
}
return isSucceeded
}
有什么问题?
答案 0 :(得分:2)
请避免从异步运行代码的方法返回数据。
您的逻辑可以像这样。
private fun SaveUserToDatabase(username: String){
val uid = mAuth.uid
val user = User(uid!!, username)
myRef = database.getReference("/users/$uid")
myRef.setValue(user).addOnCompleteListener{
if(it.isSuccessful){
updateView(it.isSuccessful);
}
}
}
private fun updateView(isSuccess: Boolean){
if (isSuccess) {
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show()
val intent = Intent(this, LatestTransactions::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.putExtra(CURRENT_USER, mAuth.currentUser.toString())
startActivity(intent)
} else {
register_tv_error.text = "Couldn't save user"
}
有关更多信息,请阅读this question
中的asynchronous-vs-synchronous