不调用RealTimeDatabase的OnCompleteListener

时间:2019-08-18 21:24:58

标签: android firebase firebase-realtime-database kotlin

我想知道为什么不调用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
}

有什么问题?

1 个答案:

答案 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