Home > other >  Trying to get IDS of all documents in firebase, android
Trying to get IDS of all documents in firebase, android

Time:06-08

private fun queryCollection() {
    val users = arrayListOf<User2>()

    db.collection(USER2_COLLECTION_NAME).get()
        .addOnCompleteListener { task ->

            if (task.isSuccessful) {
                val userDocuments = task.result
                Log.e("a7a", "task result size: ${task.result.size()}")
                for (userDocuments2 in userDocuments) {
                    try {
                        val userObject = userDocuments2.toObject<User2>()
                        users.add(userObject)
                        Log.e("a7a", "user documents size: ${userDocuments.size()}")
                        Log.e("a7a", "users array size: is ${users.size}")

                        for (i in 0 until userDocuments.size()) {
                            users[i].userId = userDocuments2.id
                        }

                        val adapter = AdapterClass2(users)
                        binding?.rvUsers2?.layoutManager = LinearLayoutManager(this)
                        binding?.rvUsers2?.visibility = View.VISIBLE

                        binding?.rvUsers2?.adapter = adapter
                    } catch (e: Exception) {
                        Log.e("a7a orror", "$e")

                    }
                }
            } else {
                Log.e("a7a error", "${task.exception?.message}")
            }
        }
}

I'm trying to fetch the id's of all documents in my collection, I've made an array list of an user in which I am storing the documents into a recycler view to show them. users is an array list of Users2 which is a dataclass that contains the paramter id. What I'm trying to do is to that I'm trying to get the id of the document and bind it to the user[i] which is supposedly in a for loop. However, when I run it, I always get the error

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

because the users's size is only one, although it's supposed to be two because the recycler view succesffuly shows to useres, and iI'm pasing users in the adapter of the recycler vierw as hshown, any help?

CodePudding user response:

When your inner for loop runs for the first time:

                        for (i in 0 until userDocuments.size()) {
                            users[i].userId = userDocuments2.id
                        }

There will only have been one item added to users, when you previously called add() (also for the first time). That's why it only has one item, as the error message says.

Maybe you don't want that inner loop at all and instead do something only after you've processed all the documents in the outer for loop (not inside the document for loop).

  • Related