Home > Back-end >  How to retrieve data from firestore and store it to array (Kotlin- Android Studio)
How to retrieve data from firestore and store it to array (Kotlin- Android Studio)

Time:04-18

I have a database in firebase where users collection consists of several fields but only the email of every user is essential. I will like to retrieve it from the firebase database and store it in ArrayList or hashmap. Can you please help me with the implementation in android studio using Kotlin?

Example of firebase collection:

Collection:Users

 ->document1->email1

 ->document2->email2

CodePudding user response:

From firestore documentation - https://firebase.google.com/docs/firestore/query-data/get-data#kotlin ktx_3

You need to create reference of the firestore database. Then get the data from the collection and this will return you all the documents of a collection. In iteration convert the documents to the user class that you need to create which will have email field.

 db.collection("users")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {
                val users = document.toObject(Users::class.java)
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents: ", exception)
        }

Hope this will help you

  • Related