繁体   English   中英

如何使用Kotlin从Firebase数据库中检索数据?

[英]How to retrieve data from a Firebase database with Kotlin?

这是我在Firebase上传的模型:

public class OnlineMatch{

private User user1;
private User user2;

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

}

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

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

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

在此输入图像描述 如果我展开一个节点,我可以完美地看到我的对象:OnlineMatch(User1,User2)

现在我想查询db并获得一个ArrayList'<'OnlineMatch'>'。 我已经找到了Firebase文档,但我发现没什么用处。 我能怎么做? 提前致谢。

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

Kotlin ,不需要吸气剂和固定剂。 确实在幕后存在这些函数,但不需要明确定义它们。 要设置这些字段,可以使用以下代码:

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

非常重要的是,不要忘记在您的OnlineMatch类中添加Firebase所需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())
        }
    }
})

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM