【发布时间】:2021-01-24 20:41:57
【问题描述】:
我正在使用 ViewModel 从 Firebase 获取数据,当我尝试将数据与 textView 绑定时,我看到了下一个错误。
java.lang.RuntimeException:无法启动活动 组件信息{com.example.pruebafirebase/com.example.pruebafirebase.MainActivity}: java.lang.IndexOutOfBoundsException:索引:0,大小:0
class MainActivity : AppCompatActivity() {
private val viewModel by lazy {ViewModelProvider(this).get(MyViewModel::class.java)}
private var dataList = mutableListOf<User>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel.fetchUserData().observe(this, Observer {it: MutableList<User>!
dataList = it
})
bindView(dataList[0])
}
fun bindView(users: User) {
nameOne.text = users.name
lastOne.text = users.last
}
}
【问题讨论】:
-
在你的观察者函数中移动
bindView(dataList[0])。否则,您将尝试在将任何内容添加到列表之前检索该值。 -
完美,我已经花了一个多小时试图弄清楚。谢谢
标签: android firebase kotlin mvvm