简体   繁体   English

如何从 kotlin 上的 firebase 数据库中获取键和值

[英]How go get both both key and value from firebase database on kotlin

I'm new to android development and im having a bit of problem with firebase database.我是 android 开发的新手,我在使用 firebase 数据库时遇到了一些问题。 I'm creating a app somewhat similar to e-commerce application.我正在创建一个有点类似于电子商务应用程序的应用程序。

category1
    child1
         name: nameOfChild1
         value: value
    child2
         name: nameOfChild2
         value: value
    child3

This is how my database is structured.这就是我的数据库的结构。 im using我在用着

dbref = FirebaseDatabase.getInstance().getReference("requiredCategory")
        dbref.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {
                    for (productSnapshot in snapshot.children) {
                        val product = productSnapshot.getValue(Product::class.java)
                        productlist.add(product!!)
                    }
                    productrecyclerview.adapter = productAdapter(productlist)
                }
            }

And Product class is Product类别是

data class Product(
    var id: String? = null,
    var price: String? = null,
)

Instead i would like to change my structure to相反,我想将我的结构更改为

category1
    child1
      nameOfNested1: value
      nameOfNested2: value
    child2
      nameOfNested1: value
      nameOfNested2: value
    child3
      nameOfNested1: Value
      nameOfNested2: value

category2
    child1
    child2
    child3

I want to retrive both the key: nameOfNested and value:value .How do i go on and change the code get both the id and value?我想检索这两个key: nameOfNestedvalue:value 。我如何继续并更改代码以获得 id 和值? Thanks in Advance提前致谢

If you also want to get the key of each product, you can do so with:如果您还想获得每个产品的密钥,您可以这样做:

for (productSnapshot in snapshot.children) {
    val key = productSnapshot.key // 👈
    val product = productSnapshot.getValue(Product::class.java)
    ...

Let me answer with what i got working and also be a bit more specific about what i was trying to accomplish让我回答我的工作,并更具体地说明我试图完成的事情

First of all, let me start with what i was doing.首先,让我从我正在做的事情开始。 i had a Firebase Realtime Database that looked like this (Only an example for demonstration purpose)我有一个看起来像这样的 Firebase 实时数据库(Only an example for demonstration purpose)

Students
   Riya
     name: Riya 
     class: 10
   Benson
     name: Benson
     class: 9
   Merlin
     name: Merlin
     class: 7

I Made a student class that looks like this我做了一个看起来像这样的学生班

data class Student(
    var name: String? = null,
    var class: String? = null,
)

I found a snippet online that would retrieve data from db that is given below我在网上找到了一个片段,可以从下面给出的数据库中检索数据

dbref = FirebaseDatabase.getInstance().getReference("Students")
        dbref.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {
                    for (studentSnapshot in snapshot.children) {
                        val student = studentSnapshot.getValue(Student::class.java)
                       studentlist.add(student!!)
                    }
                    myrecyclerview.adapter = thisAdapter(studentlist)
                }
            }

It gave a Array that look something like this它给出了一个看起来像这样的数组

[Student(name=Riya, class=10), Student(name=Benson, class=9), Student(name=Merlin, class=7)]

As you can see, the structure that i was using was inefficient and i want to change it.如您所见,我使用的结构效率低下,我想更改它。 Also, instead of a single Students refence i wanted to add child which holds the students based on the class they are in. Also i wanted to add age property to each student as well.此外,我想添加一个孩子,而不是一个单一的Students参考,它根据学生所在的班级来容纳学生。我还想为每个学生添加age属性。 So i came up with a structure that looks like this所以我想出了一个看起来像这样的结构

Students
   Class7
      Joe: 12
      Mary: 11
      Ann: 12
   Class8
      Michael: 12
      Lucy: 12
   Class9
      Ricko: 15
      Anna: 14

Staff
    class7
      Janet:25
      Bob: 34

What i was having issue with getting Both the Key and value at the same time.我在同时获取密钥和值时遇到的问题。 what at the time i was using was当时我用的是

FirebaseDatabase.getInstance()
            .getReference("Students")
            .child(requiredClass)
            .addValueEventListener(object : ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot) {
                    if (snapshot.exists()) {
                        for (studentSnapshot in snapshot.children) {
                     val student = studentSnapshot.getValue(Student::class.java)
                            studentlist.add(student!!)
                        }

It was not working with what i had.. It was looking for ids name and age .它不能与我所拥有的一起工作..它正在寻找 ids nameage (i renamed the class to age in the Student class) (我将班级重命名为Student classage

I got it working by doing something like this我通过做这样的事情让它工作

FirebaseDatabase.getInstance()
            .getReference("Students")
            .child(requiredClass)
            .addValueEventListener(object : ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot) {
                    if (snapshot.exists()) {
                        for (studentSnapshot in snapshot.children) {

                            val student = Student()
                            student.name = studentSnapshot.key.toString()
                            student.age = studentSnapshot.value.toString()
                            studentlist.add(student!!)
                        }

This works fine and returns a array that i wanted.这工作正常并返回我想要的数组。

I know most of that explanation was unnecessary.我知道大部分解释都是不必要的。 i wanted to clarify what my situation was.我想澄清一下我的情况。 Also my solution might be the worst.我的解决方案也可能是最糟糕的。 If anyone have a better solution, i'm all ears...如果有人有更好的解决方案,我洗耳恭听......

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

相关问题 如何使用 snapshotChanges() 方法获取键值和过滤数据? - How to use snapshotChanges() method to get both key value and filter the data? 如何同时运行 svelte 和 go - How to run both svelte and go 如何使用 Kotlin 从 Firebase 获取特定数据 - How to get specific data from Firebase with Kotlin 如何删除 firestore 上的键值对? (不只是价值或关键两者) - how to delete key-value pair on firestore? (not just value or key both of them) 如何同时运行 getDownloadURL 和 getMetaData 并将结果输入同一个 object? Firebase 存储 - How do I run both getDownloadURL and getMetaData at once and get the results into the same object? Firebase Storage 如何在 firebase 数据库中使用 kotlin 协程 - How to use kotlin coroutines in firebase database 如何更新 firebase 实时数据库 (JavaScript) 中键的值 - How to update the value of a key in firebase Realtime database (JavaScript) 如何同时为移动和桌面制作 Flutter Firebase 应用程序 - How to do a Flutter Firebase app for both Mobile and Desktop at the same time 显示来自 Firebase 数据库的密钥 - Display a Key from Firebase Database 如何从 Firebase 实时数据库中获取数据到 Flutter 的列表中? - How to get data from Firebase Realtime Database into list in Flutter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM