Erbez
Erbez

Reputation: 321

Text not setting to mutable string

I'm trying to add text to a variable and use that in the dialog but it wont put anything in. Here is my code:

var dex = ""
firestoreInstance.collection("test").whereEqualTo("module", listMod[spinnerMod.selectedItemPosition].ID).get().addOnCompleteListener { task ->
     if (!task.result.isEmpty) for (document in task.result) {
          dex += "Success"
     } else {
          dex += "Fail"
     }
}
val builder = AlertDialog.Builder(this)
builder.setMessage(dex).setTitle(dex).show()

and this is the output:

enter image description here

What am I missing?

Upvotes: 0

Views: 65

Answers (1)

zsmb13
zsmb13

Reputation: 89608

Firebase Tasks execute asynchronously. What's happening is that you fire off your query and immediately put up an AlertDialog while dex is still an empty string. Then, when the query completes, it changes dex's value, but it's never read again.

You could instead show the dialog when the task completes:

firestoreInstance.collection("test").whereEqualTo("module", listMod[spinnerMod.selectedItemPosition].ID).get().addOnCompleteListener { task ->
     var dex = ""
     if (!task.result.isEmpty) for (document in task.result) {
          dex += "Success"
     } else {
          dex += "Fail"
     }
    val builder = AlertDialog.Builder(this)
    builder.setMessage(dex).setTitle(dex).show()
}

Upvotes: 1

Related Questions