【问题标题】:Add parsed data to list将解析的数据添加到列表
【发布时间】:2020-12-26 15:23:07
【问题描述】:

所以我创建了这个函数来为我的列表生成假值:

private fun generateFakeValues(): List<Torrent> {
    val values = mutableListOf<Torrent>()

    val torrent1 = Torrent()
    torrent1.name = "Big Buck Bunny"
    torrent1.downloadSpeed = 0.00
    torrent1.uploadSpeed = 0.00
    torrent1.downloaded = 59.23
    torrent1.length = 263.64

    values.add((torrent1))

    return values
}

而且效果很好。现在我添加了一个 Http 请求并想解析数据但项目不在列表中:

private fun getTorrents(): List<Torrent> {
    var torrents = mutableListOf<Torrent>()
    val request = Request.Builder()
        .url("...")
        .build()

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            e.printStackTrace()
        }
        override fun onResponse(call: Call, response: Response) {
            response.use {
                if (!response.isSuccessful) {
                    throw IOException("Unexpected code $response")
                }
                torrents = gson.fromJson(response.body!!.string(), mutableListOf<Torrent>()::class.java)
            }
        }
    })
    return torrents
}

我做错了什么?

【问题讨论】:

  • 你遇到了什么错误?另外,如果你可以发布你试图解析的 json
  • 没有错误。我只想知道如何从 onResponse 函数中返回一些东西,以便我可以更新我的列表

标签: android kotlin gson okhttp


【解决方案1】:

由于网络调用发生在后台线程上。您必须将数据发布到 UI 线程,例如

activity.runOnUiThread({/*add to adapter and notify data change to adapter*/})

view.post({/*add to adapter and notify data change to adapter*/})

【讨论】:

    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多