【问题标题】:Android Kotlin: How to update recyclerView after async call? getting CalledFromWrongThreadExceptionAndroid Kotlin:异步调用后如何更新 recyclerView?获取 CalledFromWrongThreadException
【发布时间】:2019-02-09 20:03:22
【问题描述】:

我正在尝试进行异步调用,然后更新RecyclerView。很像这个问题中概述的内容:RecyclerView element update + async network call

但是,当我尝试执行此操作时,我收到此错误: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

这是我的代码(主要问题在于 setAlbums 函数):

class AlbumActivity : AppCompatActivity() {

    protected lateinit var adapter: MyRecyclerViewAdapter
    protected lateinit var recyclerView: RecyclerView
    var animalNames = listOf("nothing")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_album)

        recyclerView = findViewById<RecyclerView>(R.id.rvAnimals)
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = MyRecyclerViewAdapter(this, animalNames)
        recyclerView.adapter = adapter

        urlCall("https://rss.itunes.apple.com/api/v1/us/apple-music/coming-soon/all/10/explicit.json")

    }

    private fun urlCall(url: String) {

        val client = OkHttpClient()
        val request = Request.Builder().url(url).build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {}
            override fun onResponse(call: Call, response: Response) = getJSON(response.body()?.string())
        })
    }

    fun getJSON(data: String?) {

        val gson = Gson()
        val allAlbums = ArrayList<Album>()

        val jsonResponse = JSONObject(data)
        val feed = jsonResponse.getJSONObject("feed")
        val albums = feed.getJSONArray("results")

        for (i in 0 until albums.length()) {
            val album = albums.getJSONObject(i)
            allAlbums.add(gson.fromJson(album.toString(), Album::class.java))
        }
        setAlbums(allAlbums)
    }


    fun setAlbums(albums: ArrayList<*>) {

        animalNames = listOf("sue", "betsie")
        adapter.notifyDataSetChanged() // This is where I am telling the adapter the data has changed
    }

    internal inner class Album {
        var artistName: String? = null
        var name: String? = null
    }
}

有人知道我遇到的问题吗?

【问题讨论】:

    标签: java android asynchronous kotlin android-recyclerview


    【解决方案1】:

    你需要像这样在你的主线程上执行你想要的代码:

    runOnUiThread(new Runnable() {
    
    @Override
    public void run() {
        //update your UI
        }
    });
    

    【讨论】:

      【解决方案2】:

      您的Callback 函数将在后台线程上调用。部分原因是因为 OkHttp 不是 Android 特定的库,所以它不知道 Android 的主应用程序线程。

      您需要做一些事情来更新主应用程序线程中的 UI。现代选项包括:

      • 让您的 Callback 更新您的 UI 观察到的 MutableLiveData,这样 UI 将在主应用程序线程上获得更新
      • 使用using OkHttp with RxJava 的现有配方

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-15
        • 2020-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多