0

I wonder why the onCompleteListener is not called but the data are saved to the FireBaseDatabase successfully. I just want to say: if the data are saved to FireBaseDatabase, set isSuccedded to true, but this does not happen. isSucceeded is always 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"
}

and the function:

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
}

What is the Problem?

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
MisterNowhere
  • 605
  • 1
  • 6
  • 13

1 Answers1

2

Please avoid returning data from method that runs asynchronously code.

Your logic can be like this.

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"
}

For more info read asynchronous-vs-synchronous in this question

Mohamed Nageh
  • 1,963
  • 1
  • 19
  • 27