异步更新视图

时间:2019-04-05 13:30:44

标签: android kotlin kotlin-coroutines thread-exceptions

我正在尝试用我想异步获取的来自网络的数据填充recyclerview

我有一个名为loadData()的函数onCreateView(),该函数首先使加载指示器可见,然后调用suspend函数加载数据,然后尝试通知视图适配器进行更新。

但是在这一点上,我得到以下异常:

  

android.view.ViewRootImpl $ CalledFromWrongThreadException:仅   创建视图层次结构的原始线程可以触摸其视图。

令我感到惊讶的是,我的理解是只有我的get_top_books()函数在不同的线程上被调用,并且以前,当我显示加载指示符时,我显然在正确的线程上。

那为什么会引发此运行时异常?

我的代码:

class DiscoverFragment: Fragment() {

    lateinit var loadingIndicator: TextView
    lateinit var viewAdapter: ViewAdapter
    var books = Books(arrayOf<String>("no books"), arrayOf<String>("no books"), arrayOf<String>("no books"))

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val viewFrame = layoutInflater?.inflate(R.layout.fragment_discover, container, false)

        val viewManager = GridLayoutManager(viewFrame!!.context, 2)
        viewAdapter = ViewAdapter(books)
        loadingIndicator = viewFrame.findViewById<TextView>(R.id.loading_indicator)

        val pxSpacing = (viewFrame.context.resources.displayMetrics.density * 8f + .5f).toInt()

        val recyclerView = viewFrame.findViewById<RecyclerView>(R.id.recycler).apply {
            setHasFixedSize(true)
            layoutManager = viewManager
            adapter = viewAdapter
            addItemDecoration(RecyclerViewDecorationSpacer(pxSpacing, 2))
        }

        loadData()

        return viewFrame
    }

    fun loadData() = CoroutineScope(Dispatchers.Default).launch {
        loadingIndicator.visibility = View.VISIBLE
        val task = async(Dispatchers.IO) {
            get_top_books()
        }
        books = task.await()
        viewAdapter.notifyDataSetChanged()
        loadingIndicator.visibility = View.INVISIBLE
    }
}

4 个答案:

答案 0 :(得分:3)

调用books = task.await()后,您不在UI线程中。这是因为您使用了CoroutineScope(Dispatchers.Default)。将其更改为Dispatchers.Main

fun loadData() = CoroutineScope(Dispatchers.Main).launch {
        loadingIndicator.visibility = View.VISIBLE
        val task = async(Dispatchers.IO) {
            get_top_books()
        }
        books = task.await()
        viewAdapter.notifyDataSetChanged()
        loadingIndicator.visibility = View.INVISIBLE
    }

答案 1 :(得分:1)

调用books = task.await()后,您不在UI线程中。您应该在主线程中运行所有与UI相关的代码。为此,您可以使用Dispatchers.Main

CoroutineScope(Dispatchers.Main).launch {
    viewAdapter.notifyDataSetChanged()
    loadingIndicator.visibility = View.INVISIBLE
}

或使用Handler

Handler(Looper.getMainLooper()).post { 
    viewAdapter.notifyDataSetChanged()
    loadingIndicator.visibility = View.INVISIBLE
}

或者您可以使用Activty实例来调用runOnUiThread方法。

activity!!.runOnUiThread {
    viewAdapter.notifyDataSetChanged()
    loadingIndicator.visibility = View.INVISIBLE
}

答案 2 :(得分:0)

与UI相关的语句应该在UI线程中执行,我不能仅从链接的代码中得知,但是也许您正在通过get_top_books()函数更改UI。

只需将相关的UI代码放在这样的UI线程中

runOnUiThread(
    object : Runnable {
        override fun run() {
            Log.i(TAG, "runOnUiThread")
        }
    }
)

答案 3 :(得分:0)

Dispatchers.Default更改为Dispatchers.Main并将我的kotlinx-coroutines-android版本升级为1.1.1就是成功的秘诀。

更改

val task = async(Dispatchers.IO) {
    get_top_books()
}
books = task.await()

books = withContext(Dispatchers.IO) {
    get_top_books()
}

也比较优雅。感谢所有特别响应@DominicFischer并希望检查我的依赖项的人。