使用Kotlin迭代firebase数据库

时间:2018-05-16 13:32:52

标签: loops firebase firebase-realtime-database kotlin

我创建了一个数组(我认为):

var recipeArray: List<RecipeTemplate> = mutableListOf() //RecpeTemplate is a class

我已经写出了基本的Firebase代码并验证了它可以使用console.log来打印数据库中的数据。

onChildAdded()中,我现在想循环数据库并将数据添加到数组中。这就是我所拥有的:

override fun onChildAdded(snapshot: DataSnapshot?, p1: String?) {

            val children = snapshot!!.children 

            /*children.mapNotNullTo(recipeArray) {
                it.getValue(RecipeTemplate)<RecipeTemplate::class>
            } NOT SURE ABOUT THIS ONE*/


            children.forEach{
                var tempRecipe: RecipeTemplate? = null

                tempRecipe!!.recipeHeader = it.object["recipeHeaderFirebase"]
                tempRecipe!!.recipeText = it.object["recipeIngredientsTextFirebase"]
                tempRecipe!!.recipeImage = it.object["recipeImageFirebase"]

            }
        }

Here是fb数据的示例。

不确定最后一部分:it.object。我觉得它应该是别的......

1 个答案:

答案 0 :(得分:1)

要迭代,请尝试以下操作:

override fun onChildAdded(snapshot: DataSnapshot?, p1: String?) {

        val children = snapshot!!.children
        children.forEach {
        println(it.toString())
    }
}

这将在您的引用的直接子代内部迭代并检索数据。