【问题标题】:how to store data from firebase into arraylist in kotlin? [duplicate]如何将来自firebase的数据存储到kotlin中的arraylist中? [复制]
【发布时间】:2019-10-18 18:21:17
【问题描述】:

//entityList 是我的 HomeScreenEntity 类型的数组列表(两个字符串数据成员)

entityList 无法在 addOnSuccessListner 之外保留其数据?为什么?

val docRef = database.collection("DepartmentImages_C").document("DepartmentImages_C")

    docRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot data: ${document.data}")

                entityList.add(HomeScreenEntity(document["ComputerDepartment"].toString(),"ComputerDepartment"))
                entityList.add(HomeScreenEntity(document["LawDepartment"].toString(),"LawDepartment"))
                entityList.add(HomeScreenEntity(document["LiteratureDepartment"].toString(),"LiteratureDepartment"))
                entityList.add(HomeScreenEntity(document["ScienceDepartment"].toString(),"ScienceDepartment"))

                Toast.makeText(application.applicationContext,entityList[0].departmentName,Toast.LENGTH_SHORT).show() // this one is working fine

            } else {
                Log.d(TAG, "No such document")
            }
        }
        .addOnFailureListener { exception ->
            Log.d(TAG, "get failed with ", exception)
        }
    Toast.makeText(application.applicationContext,entityList[0].departmentName,Toast.LENGTH_SHORT).show()  // this toast message is giving me index out of bound error
}

entityList 无法在 addOnSuccessListner 之外保留其数据?为什么??*/

【问题讨论】:

    标签: android firebase kotlin arraylist google-cloud-firestore


    【解决方案1】:

    docRef.get() 是一个异步函数。因此,当 docRef.get() 在后台线程中工作时,toast 将被执行但不会显示您想要的内容,因为 entityList 尚未更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2018-09-13
      • 2017-06-06
      • 2021-12-20
      • 2017-06-27
      • 1970-01-01
      • 2013-05-05
      相关资源
      最近更新 更多