0

Im have a Collection called: Players Inside there each document has a value of posx and posy

i want to create an Array with Arrays for each document Like: [[posx1,posy1][[posx,posy2]...]

if i put a print inside the .addOnSuccesListener it works and prints the list but when im outside there and i try to print the list it returns empty

What i am doing wrong? Thanks

val myDB = FirebaseFirestore.getInstance()
var posiciones = ArrayList<Array<String>>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    myDB.collection("players")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {
                posiciones.add(
                    arrayOf(
                        document.get("posx").toString(),
                        document.get("posy").toString()
                    )
                )

            }
        }
        .addOnFailureListener { exception ->
            Log.d(ContentValues.TAG, "Error getting documents: ", exception)
        }
    //i get []
    println("Testing: "+ posiciones)
0

1 Answer 1

1

That's because get is asynchronous and returns immediately. Your code will go on to execute the println before anything else happens. posiciones will be empty at that time. Then, some time later when the query is complete and the database results are available, the success callback will be invoked, and the array will get populated. Only after the callback is received is it a good idea to read the contents of posiciones.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.