Android Kotlin:异步调用后如何更新recyclerView?获取CalledFromWrongThreadException

时间:2019-02-09 20:03:22

标签: java android asynchronous kotlin android-recyclerview

我正在尝试进行异步调用,然后更新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
    }
}

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

2 个答案:

答案 0 :(得分:3)

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

runOnUiThread(new Runnable() {

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

答案 1 :(得分:2)

您的Callback函数将在后台线程上调用。在某种程度上,这是因为OkHttp不是特定于Android的库,因此它对Android的主要应用程序线程一无所知。

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

  • 让您的Callback更新您的UI所观察到的MutableLiveData,这样UI才会在主应用程序线程上获得更新
  • 将现有食谱用于using OkHttp with RxJava