【问题标题】:Can't convert object of type java.lang.Boolean to type无法将 java.lang.Boolean 类型的对象转换为类型
【发布时间】:2021-12-06 11:22:15
【问题描述】:

我有一个对象的问题,即在创建对象列表时出现标题中的错误。

Kotlin 代码

 private fun readNotification() {
        val firebaseUser = FirebaseAuth.getInstance().currentUser
        val reference = FirebaseDatabase.getInstance().getReference("Notifications")
            .child(firebaseUser!!.uid)
        reference.addValueEventListener(object : ValueEventListener{
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                notificationList.clear()
                for (snapshot : DataSnapshot in dataSnapshot.children){
                    val notification = snapshot.getValue(NotificationData::class.java)!!
                    notificationList.add(notification)
                }
                notificationList.reverse()
                notificationAdapter.notifyDataSetChanged()
            }

            override fun onCancelled(error: DatabaseError) {
            }
        })
    }

对象代码

class NotificationData(
    var userId: String = "",
    var text: String = "",
    var postId: String = "",
    var isPost: Boolean = false
) {}

Firebase 结构

我知道错误在这一行,因为对象有一个布尔变量

val notification = snapshot.getValue(NotificationData::class.java)!!

我现在只是不知道如何处理它

【问题讨论】:

    标签: android kotlin firebase-realtime-database


    【解决方案1】:

    虽然我认为 Firebase JSON 映射器处理了 isBla 格式 getter,但您的 JSON 中只有一个布尔值,因此问题出现在那里是有道理的。

    您可以将布尔值更改为:

    var post: Boolean = false
    

    或者添加一个显式的@PropertyName注解:

    @PropertyName("post")
    var isPost: Boolean = false
    

    也就是说,我认为 Firebase 映射器默认处理布尔 isXyz 属性是一个有效的期望,因此建议在 SDK 的 Github 存储库中添加功能请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多