firebase - 为什么在 Kotlin 中迭代 firebase 数据库时元素值添加了两次?

标签 firebase for-loop firebase-realtime-database kotlin duplicates

我正在尝试迭代 firebase-database并将其元素添加到我的对象中。它可以工作,但由于某种原因我无法理解,它将每个元素广告两次,日志输出显示如下:

TAGZ: DataSnapshot { key = recipeHeaderFirebase, value = Tahini-Oat Cookies } 
TAGZ: DataSnapshot { key = recipeHeaderFirebase, value = Tahini-Oat Cookies }
TAGZ: DataSnapshot { key = recipeHeaderFirebase, value = Chocolate & Cinnamon Cookies }
TAGZ: DataSnapshot { key = recipeHeaderFirebase, value = Chocolate & Cinnamon Cookies }
TAGZ: DataSnapshot { key = recipeHeaderFirebase, value = Sweet Potato Muffin }
TAGZ: DataSnapshot { key = recipeHeaderFirebase, value = Sweet Potato Muffin }
TAGZ: DataSnapshot { key = recipeHeaderFirebase, value = Almond Butter Cookies }
TAGZ: DataSnapshot { key = recipeHeaderFirebase, value = Almond Butter Cookies }
Firebase-database结构看起来像这样(请注意,我现在忽略了其他元素):

FbDb

我的 Kotlin 代码如下所示:
fbdb = FirebaseDatabase.getInstance()
ref = fbdb!!.getReference("cookies")

ref!!.addChildEventListener(object: ChildEventListener {

    override fun onChildAdded(snapshot: DataSnapshot?, p1: String?) {
        val children = snapshot!!.children //DIRECT REFERENCE TO CHILD, USED FOR LOOP
        val header = snapshot!!.child("recipeHeaderFirebase")

        for(it in children) {
            var tempRecipe = RecipeTemplate()
            tempRecipe.recipeHeader = header.toString()
            Log.d("TAGZ", tempRecipe.recipeHeader)  //OUTPUT SHOWS DUPLICATE VALUES
            }
        }
    }) 

我错过了什么?我使用类似的代码成功检索了 Xcode 中的元素...

编辑 应要求提供完整代码:
package com.healthandchocolate.sjostedtafzelius.healthchocolateandroid

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.firebase.database.*

class RecipeGridView : AppCompatActivity() {

private var fbdb: FirebaseDatabase? = null
private var ref: DatabaseReference? = null
var recipeArray: MutableList<RecipeTemplate> = mutableListOf()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_recipe_grid_view)
    Log.d("TAG", "ON CREATE");

    fbdb = FirebaseDatabase.getInstance()
    ref = fbdb!!.getReference("cookies")

    ref!!.addChildEventListener(object: ChildEventListener {

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

        }

        override fun onChildMoved(p0: DataSnapshot?, p1: String?) {
            Log.d("TAG", "ON CHILD MOVED");
        }

        override fun onChildRemoved(p0: DataSnapshot?) {
            Log.d("TAG", "ON CHILD REMOVED");

        }

        override fun onCancelled(error: DatabaseError) {
            print(error)
            Log.d("TAG", "ON ERROR");

        }

        override fun onChildAdded(snapshot: DataSnapshot?, p1: String?) {
            Log.d("TAGZ", "CALLED")  //keyName of each child

            val children = snapshot!!.children //DIRECT REFERENCE TO CHILD, USED FOR LOOP
            val header = snapshot!!.child("recipeHeaderFirebase")

            for(it in children) {
                var tempRecipe = RecipeTemplate()
                tempRecipe.recipeHeader = header.toString()
                //Log.d("TAGZ", tempRecipe.recipeHeader)  //keyName of each child

                recipeArray.add(tempRecipe)
            }
        }
        }) //END FB CODE
}
}

最佳答案

每次系统将意图路由到当前事件的实例时,都会创建事件。所以函数onCreate可以多次调用。

每次调用您的函数时,您为 addChildEventListener 保存的回调函数事件被添加到监听器。此后,当事件被触发时,回调函数会被调用,就像它之前链接到监听器一样多。

为了防止这种行为,您可以定义 android:launchmode:"singleTop"在您的应用 list 文件中的标签 <activity>

这允许系统将意图路由到其他函数 onNewIntent而不是 onCreate
欲了解更多信息,请浏览:
https://developer.android.com/guide/topics/manifest/activity-element#lmode

我希望这将有所帮助。

我尽力写正确的英语,所以请随时纠正我。

关于firebase - 为什么在 Kotlin 中迭代 firebase 数据库时元素值添加了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50405727/

相关文章:

ios - Firestore API 更改 - 如何解码对象

java - 当没有无限递归方法时,是什么导致了这个堆栈溢出错误?

java - 在我的 for 循环中没有看到第二类的方法引用

android - FirebaseRecyclerAdapter、PopulateViewHolder 滚动时多次调用

Swift Firebase 查询

firebase - 函数声明中的 Cloud Functions for Firebase 通配符引用

android - 升级到最新的 android/firebase sdk,这个 azure 通知中心示例 - xamarin forms

node.js - 如何观察firebase实时数据库的变化

performance - r:嵌套索引的 for 循环操作运行速度超慢

node.js - 当我尝试初始化 Firebase 应用程序时,为什么 Google Cloud Functions 会抛出 "Invalid value for config firebase.databaseURL"错误?