How to get list of documents from a collection in Firestore Android

后端 未结 2 623
滥情空心
滥情空心 2021-01-17 18:12

My structure of Firestore database:

|
|=>root_collection
                  |
                  |=>doc1
                         |                  
            


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 18:34

    You can call collection method to get documentin the root_collections then hold documents ID which will be used to get document's collection later.

    create root collection object as:

        data class RootCollection(
            @DocumentId val id: String,
            val sampleField: String?
        ) {
           // empty constructor to allow deserialization
           constructor(): this(null, null)
        }
    

    Then get the collection using FirebaseFirestore method collection as follows:

        val querySnapshot = firestore.collection("root_collection")
                    .get()
                    .await()
        if(!querySnapshot.isEmpty) {
                 Result.SUCCESS(querySnapshot.toObjects(RootCollection::class.java))
         } else {
             Result.ERROR(Exception("No data available"))
        }
    

    Then to get collection in the document call

        firestore.collection("root_collection/$documentId/collection") 
    

    Note that I have use kotlin coroutines await method as describe in this link

    The Result class am using to save state of returned data and handle errors.

       sealed class Result {
          data class SUCCESS(val data: T) : Result()
          data class ERROR(val e: Exception): Result()
          object LOADING : Result()
       }
    

提交回复
热议问题