【问题标题】:Why does the application turn off when I want to get data from Firebase?当我想从 Firebase 获取数据时,为什么应用程序会关闭?
【发布时间】:2019-06-18 09:31:15
【问题描述】:

我正在 Kotlin 中创建适用于 Android 的 Google 地图应用,并且使用了与 Firebase 的连接。它在与 Firebase 连接时崩溃

我可以将数据添加到数据库,但是当我尝试下载数据时,应用程序崩溃了。在数据库中,我有表“城市”,其中保存了“城市”类型的对象。


 private lateinit var citiesList: MutableList<City>
...

 citiesList = mutableListOf()
        var ref = FirebaseDatabase.getInstance().getReference("cities")

        ref.addValueEventListener(object: ValueEventListener {
            override fun onDataChange(p0: DataSnapshot) {
                for ( c in p0.children) {
                    val city  = c.getValue(City::class.java)
                    citiesList.add(city)
                }
            }

和城市类:

class City ( val name: String, val latitude: Double, val longitude: Double)

应用程序在此行崩溃:

val city = c.getValue(City::class.java).

另外,我不知道为什么城市值的类型是“城市?”,而不是“城市”。也许这是问题的根源。我无法将城市添加到城市列表中:Type mismatch. Required: City, Found: City?

【问题讨论】:

  • 请同时发布逻辑输出中的堆栈跟踪
  • Class com.example.mapa.City does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped
  • 请添加您的City 课程的内容,也请回复@AlexMamo
  • 我添加了@AlexMamo

标签: android firebase firebase-realtime-database kotlin


【解决方案1】:

要解决此问题,请将您的 City 课程从:

class City ( val name: String, val latitude: Double, val longitude: Double)

class City (val name: String = "", val latitude: Double = 0.0, val longitude: Double = 0.0)

否则会报如下错误:

java.lang.RuntimeException:无法反序列化对象。 City 类没有定义无参数构造函数。如果您使用 ProGuard,请确保未剥离这些构造函数。

所以请记住,City 类中的每个字段都必须在构造函数中初始化。

【讨论】:

  • 很高兴听到它成功了 :) 非常欢迎您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 2020-08-01
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
相关资源
最近更新 更多