【问题标题】:How to retrieve data from a Firebase database with Kotlin?如何使用 Kotlin 从 Firebase 数据库中检索数据?
【发布时间】:2017-08-01 21:27:31
【问题描述】:

这是我在 Firebase 上上传的模型:

public class OnlineMatch{

private User user1;
private User user2;

public OnlineMatch(User firstPlayer, User secondPlayer) {
        this.user1 = firstPlayer;
        this.user2 = secondPlayer;
    }

}

然后我以这种方式(kotlin)将数据发送到 Firebase:

 fun createMatch(match: OnlineMatch) {
        val matchList = database.child("multiplayer").push()
        matchList.setValue(match)
    }

因此,我的数据库结构如下:

如果我展开一个节点,我可以完美地看到我的对象: OnlineMatch(User1, User2)

现在我想查询数据库并获得一个 ArrayList''。 我已经找到了 Firebase 文档,但没有发现任何有用的东西。 我能怎么做?提前致谢。

【问题讨论】:

  • 我想补充一点,我的 OnlineMatch 类具有根据 Java 约定 (camelCase) 编写的正确 setter/getter:setUser1, getUser1 ecc

标签: android firebase firebase-realtime-database kotlin


【解决方案1】:

您没有找到有用的信息,因为当您查询 Firebase 数据库时,您得到的是 Map 而不是 ArrayList。 Firebase 中的所有内容都是由键和值对构成的。对于 Firebase,使用 ArrayList 是一种反模式。 Firebase 建议不要使用数组的众多原因之一是它使安全规则无法编写。

Kotlin 中不需要getter 和setter。确实,这些功能在幕后存在,但没有必要明确定义它们。要设置这些字段,您可以使用以下代码:

val onlineMatch = OnlineMatch() //Creating an obect of OnlineMatch class
onlineMatch.user1 = userObject //Setting the userObject to the user1 field of OnlineMatch class
//onlineMatch.setUser(userObject)

正如您可能看到的,我已经评论了最后一行,因为不需要使用 setter 来设置 userObject

非常重要的是,不要忘记在 Firebase 所需的 OnlineMatch 类中添加 the no argument constructor

public OnlineMatch() {}

编辑:

要实际获取数据,只需在所需节点上放置一个侦听器,然后将数据从dataSnapshot 对象中取出到 HashMap 中。

val map = HashMap<String, OnlineMatch>()

然后像这样简单地遍历HashMap

for ((userId, userObject) in map) {
    //do what you want with them
}

或者直接使用下面的代码:

val rootRef = firebase.child("multiplayer")
rootRef.addListenerForSingleValueEvent(object : ValueEventListener {
    override fun onCancelled(error: FirebaseError?) {
        println(error!!.message)
    }

    override fun onDataChange(snapshot: DataSnapshot?) {
        val children = snapshot!!.children
        children.forEach {
            println(it.toString())
        }
    }
})

希望对你有帮助。

【讨论】:

  • 谢谢@Alex Mamo,但我还是有麻烦。如何获得 HashMap ? PS:感谢 Kotlin 的提示,是的,我有空的构造函数。
猜你喜欢
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 2020-07-22
  • 2022-09-29
  • 1970-01-01
相关资源
最近更新 更多