android - Android Kotlin API请求|在gson流程之后访问列表

标签 android api kotlin gson okhttp

我试图在api请求后访问“mainactivity”-> StartActivity中的列表:

“mainactivity”-> StartActivity:


class StartActivity : AppCompatActivity() {


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

        fetchJson()



        ...



    }
    fun fetchJson() {
        println("Attempting to Fetch JSON")

        val url = "https://....."
        val request = Request.Builder().url(url).build()
        val client = OkHttpClient()
        client.newCall(request).enqueue(object : Callback {

            override fun onResponse(call: Call, response: Response) {
                val body = response.body?.string()

                val gson = GsonBuilder().create()

                val statsVideoList: List<StatsVideo> = gson.fromJson(body, Array<StatsVideo>::class.java).toList()
                for (jetpack_featured_media_url in statsVideoList) {
                    println("The link is${jetpack_featured_media_url}")
                }

            }


            override fun onFailure(call: Call, e: IOException) {
                println("Failed to execute request")
            }
        })
    }
}

class StatsVideo (val id: Int, val status: String , val title: Title, val jetpack_featured_media_url: String, val link: String)

class Title (val rendered: String)

现在我想在此 Activity (StartActivity)中使用该列表。例如。在PicView中将毕加索的jetpack_featured_media_url加载到ImageView中。

如何访问此字符串?

现在,我想从 component1 中获得url /字符串 jetpack_featured_media_url 并使用毕加索加载它们。

我的代码:
Picasso.get().load(statsVideoList.component1().jetpack_featured_media_url).into(imageView)

但是在应用启动时,我收到此错误

020-05-10 07:26:42.397 17384-17457/com.example.exampleE/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
    Process: com.example.example, PID: 17384
    java.lang.IllegalStateException: Method call should happen from the main thread.
        at com.squareup.picasso.Utils.checkMain(Utils.java:127)
        at com.squareup.picasso.RequestCreator.into(RequestCreator.java:679)
        at com.squareup.picasso.RequestCreator.into(RequestCreator.java:665)
        at vision.spectre.lernbox.StartActivity$fetchJson$1.onResponse(Startseite.kt:68)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:504)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
Method call should happen from the main thread.

但是,如果我现在想创建一个按钮来启动一个新的 Activity ,并用它“转移”一个字符串
val buttonLatestVid = findViewById<ImageButton>(R.id.imageButton)
        buttonLatestVid.setOnClickListener {
            val intent = Intent(this, LatestVideoDetailActivity::class.java)
            intent.putExtra("VideoLink", statsVideoLost.component1().jetpack_featured_media_url)
            startActivity(intent)
        }

staatsVideoList无法访问,因为它不在onResponse 的
但是,如果我在onResponse中创建按钮,则Intent会给我这个错误:
None of the following functions can be called with the arguments supplied: public constructor Intent(packageContext!, Context!, cls:Class<*>!) defined in android.content.Intentpublic constructor Intent(action: String!, uri: Uri!) defind in android.content.Intent

最佳答案

RequestCreator.into()调用应从主线程进行。只需在执行任何UI更改之前更改线程即可。

如果您使用协程:

Picasso.get().load(statsVideoList.component1().jetpack_featured_media_url).also {
    withContext(Dispatchers.Main.immediate) {
        it.into(imageView)
    }
}

如果您不这样做:

Picasso.get().load(statsVideoList.component1().jetpack_featured_media_url).also {
    runOnUiThread {
        it.into(imageView)
    }
}

关于android - Android Kotlin API请求|在gson流程之后访问列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61701939/

相关文章:

android - LAST_TIME_CONTACTED 返回 0

Java readline() 保持套接字打开

api - API 可以作为自定义 Assets 添加到 G-reg 中吗?

performance - 如何获得一个函数在 Kotlin 中测试函数性能所需的时间

java - 客户端(Java)未连接到服务器(Kotlin)Android Studio,出了什么问题?

android - 接口(interface)中的属性不能有支持字段

android - 如何将 32 位 .so 文件转换为适用于 Android 的 64 位 .so 文件

android - UNITY Application.OpenUrl() 不适用于 Android 7 Nougat

ios - 我们如何将具有库的 sdk/Framework 共享给其他项目?

python - 字典中的字典中的字典到 Pandas 数据框