【问题标题】:Kotlin firebase read child of child data does not workKotlin firebase 读取子数据的子数据不起作用
【发布时间】:2021-11-07 18:48:10
【问题描述】:

我试图在 kotlin 端读取 firebase 数据。我可以阅读一个孩子的data(.child("user")),但如果我尝试在“id”下阅读data(.child("user").child("id")),它会崩溃。

我尝试了所有方法,但仍然无法弄清楚。谁能帮帮我?

此外,当我从 iOS 端读取数据时,它只需添加 .child(path) func 即可,但在 Kotlin 端,它不起作用

private lateinit var database : DatabaseReference
private lateinit var sectionRecyclerView: RecyclerView
private lateinit var sectionArrayList : ArrayList<SermonSection>


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_section)

    sectionRecyclerView = findViewById(R.id.sectionList)
    sectionRecyclerView.layoutManager = LinearLayoutManager(this)
    sectionRecyclerView.setHasFixedSize(true)

    sectionArrayList = arrayListOf<SermonSection>()
    getData()

}

private fun getData() {

    //Database Declaration
    database = FirebaseDatabase.getInstance().reference.child("user").child("id")
    database.addValueEventListener(object : ValueEventListener {

        override fun onCancelled(error: DatabaseError) {
            println("ERROR is --------> " + error)
        }

        override fun onDataChange(snapshot: DataSnapshot) {
            if (snapshot.exists()){
                for (userSnapShot in snapshot.children) {
                    val user = userSnapShot.getValue(SermonSection::class.java)
                    sectionArrayList.add(user!!)
                }
                sectionRecyclerView.adapter = SectionAdapter(sectionArrayList)
            }
        }

    })

}

对于 SermonSection 类只有两个字符串值 前任)。 细节部分 章节标题

【问题讨论】:

  • 我很难理解问题所在。如果应用程序崩溃,则会有一条错误消息和堆栈跟踪写入其 logcat 输出。请找到这个,并编辑您的问题以包含它们 - 以及产生该错误的最少代码。
  • 如果应用程序崩溃,会有一个堆栈跟踪。请在 logcat 上查找,并将其添加到您的问题中。请回复@。
  • @FrankvanPuffelen 错误说 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.ttolc_android, PID: 2011 com.google.firebase.database.DatabaseException: Can't convert object of type java .lang.String 输入 com.example.ttolc_android.SermonSection

标签: android firebase kotlin firebase-realtime-database


【解决方案1】:

如果要获取detailSection & sectionTitle 并保存到SermonSection 对象,则需要读取下的child id密码

这个:

database = FirebaseDatabase.getInstance().reference.child("user").child("id").child("password")

【讨论】:

  • 密码是一个键值,所以不需要用 func child() 调用它。它也发生了同样的崩溃。
猜你喜欢
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
相关资源
最近更新 更多