【问题标题】:Index problem in mutableListOf with LiveData and ViewModel带有 LiveData 和 ViewModel 的 mutableListOf 中的索引问题
【发布时间】: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


【解决方案1】:

问题是observer 是一个异步操作,所以这可能发生在bindView 行执行之后。

viewModel.fetchUserData().observe(this, Observer {it: MutableList<User>!
    bindView(dataList[0])
})

代码行以线性方式编写,但代码执行不是线性的,在执行之前的bindView(dataList[0]) 时,上面的observer 已设置,但dataList = it 可能发生与否,很可能没有。

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 2019-07-17
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多