这是我上传到 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'<'OnlineMatch'>'。 我已经找到了 Firebase 文档,但没有发现任何有用的信息。 我能怎么做?提前致谢。
最佳答案
您没有找到有用的东西,因为当您查询 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
类中添加无参数构造函数
。
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())
}
}
})
希望对您有所帮助。
关于android - 如何使用 Kotlin 从 Firebase 数据库中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45447942/