【问题标题】:Firebase keeps removing all entries instead for only the specific oneFirebase 不断删除所有条目,而不是仅删除特定条目
【发布时间】:2019-06-06 14:51:03
【问题描述】:

我根本无法从 Firebase 中删除特定条目: Picture of the Firebase database

它总是删除整个数据库。

我已经尝试过这些代码:

fun removeLobbyFromDatabase() {
    // lobbyId is string value of the key
    val query = db.child(lobbyId)

    query.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            snapshot.ref.removeValue()
        }

        override fun onCancelled(p0: DatabaseError) {}
    })
}

fun removeLobbyFromDatabase() {
    val ref = db.ref
    ref.child(lobbyId).removeValue()
}

还有(但没有任何反应)

fun removeLobbyFromDatabase() {
    db.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            snapshot.children.forEach { lobby -> if (lobby.key == lobbyId) lobby.ref.removeValue() }
        }

        override fun onCancelled(p0: DatabaseError) {}
    })
}

db 来自这里(我使用的是 Dagger 2):

    @Provides
    @Singleton
    fun getFirebaseRef(): DatabaseReference = 
    FirebaseDatabase.getInstance().getReference("lobbies")

我怎样才能删除大厅(条目)而不是整个数据库?

>>> 编辑,已解决

这很尴尬,但我在调试器中注意到 lobbyId 是空的。然后我意识到我在其他地方清除了那个字符串。我对此太自信了。感谢人们在这里付出的努力,在解决我的错误后,这段代码运行得很好:

fun removeLobbyFromDatabase() = db.child(lobbyId).removeValue()

所以,如果你正在阅读这里并且遇到同样的问题,请务必调试!

【问题讨论】:

  • lobbyId的值是多少?
  • 键的常量字符串值,本例中例如:“-LghCdSV-5HWF-tqoqiy”
  • 所以你的解决方案正是我的答案,对吧?
  • 嘿,是的。这给了我一个教训——即使你 100% 确定也要调试。谢谢

标签: android firebase firebase-realtime-database kotlin


【解决方案1】:

要从 Firebase 实时数据库中删除项目,无需附加侦听器,您可以直接在引用上调用 removeValue() 函数,如下所示:

val rootRef = FirebaseDatabase.getInstance().getReference()
val lobbyIdRef = rootRef.child("lobbies").child("-LghCdSV-5HWF-tqoqiy")
lobbyIdRef.removeValue()

您还可以使用addOnCompleteListener() 来查看删除操作何时完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2018-10-16
    • 1970-01-01
    相关资源
    最近更新 更多