Home > Enterprise >  How to load array data from Firestore?
How to load array data from Firestore?

Time:06-16

I don't know how to load this array field (IllnessHistory), I have searched on google for it, but no one works. Anyone can help me with this? Here is my code and screenshot of my Firestore structure:

    override suspend fun loadHistoryGiveDonor(userId: String): ArrayList<GiveDonor> {
        val data = ArrayList<GiveDonor>()

        giveDonorCollectionReference.whereEqualTo(Constants.USER_ID, userId).get()
            .addOnSuccessListener { documents ->
                for (document in documents) {
                    data.add(
                        GiveDonor(
                            document.id,
                            document.data[Constants.USER_ID].toString(),
                            document.data[Constants.NAME].toString(),
                            document.data[Constants.WHATSAPP_NUMBER].toString(),
                            document.data[Constants.DATE_BIRTH].toString(),
                            document.data[Constants.GENDER].toString(),
                            document.data[Constants.BLOOD_TYPE].toString(),
                            document.data[Constants.PROVINCE].toString(),
                            document.data[Constants.CITY].toString(),
                            document.data[Constants.DISTRICT].toString(),
                            document.data[Constants.BODY_WEIGHT].toString(),
                            document.data[Constants.BODY_HEIGHT].toString(),
                            document.data[Constants.CURRENT_CONDITION].toString(),
                            document.data[Constants.LAST_DONOR_DATE].toString(),
                            document.data[Constants.EVER_COVID].toString(),
                            document.data[Constants.COVID_STATUS].toString(),
                            document.data[Constants.RECOVERED_DATE].toString(),
                            ArrayList(),
                            document.data[Constants.NOTE].toString(),
                        )
                    )
                }
                Log.d("ResultsizeofGive", "${data.size.toString()} ${documents.toString()}")
            }.await()
        return data
    }

enter image description here

CodePudding user response:

To get the content of the "IllnessHistory" array as a list of GiveDonor objects, then you should create a new class that contains that specific list like this:

data class GiveDonorDoc (
    @get:PropertyName("IllnessHistory")
    @set:PropertyName("IllnessHistory")
    @PropertyName("IllnessHistory")
    var illnessHistory: MutableList<GiveDonor>? = null
)

Now to read the data, you can simply use:

val illnessHistory = document.toObject(GiveDonor.class).illnessHistory

I have also written an article on this topic called:

  • Related