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

这是我在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)

现在我想查询数据库并获得一个ArrayList”。 我已经find了Firebase文档,但是我没有发现任何用处。 我能怎么做? 提前致谢。

你没有find有用的东西,因为当你查询一个Firebase数据库时,你会得到一个Map而不是ArrayList 。 Firebase中的所有内容都是按键和值组成的。 谈到Firebase时,使用ArrayList是一种反模式。 Firebase建议不要使用arrays的原因之一是它使得安全规则无法写入。

Kotlin ,没有必要获得吸引者和二传手。 在幕后,这些function是存在的,但是没有必要明确地定义它们。 要设置这些字段,可以使用下面的代码:

 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() 

然后简单地遍历这个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()) } } }) 

希望能帮助到你。