gpt4 book ai didi

android - 使用 kotlin 协程处理 retrofit 2.6 的无互联网连接错误

转载 作者:行者123 更新时间:2023-11-29 16:30:11 31 4
gpt4 key购买 nike

我正在使用带有 kotlin 协程的改造 2.6 来进行 API 调用而不阻塞 UI 线程,我成功了,但是当我关闭互联网连接时应用程序崩溃了。 logcat 错误是:E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1

这是我的代码:

private fun handleIntent(slug: String) {
val service = UtilityMethods.migrationTimeService()

UtilityMethods.showView(loading_view)
UtilityMethods.hideView(network_error_msg)

CoroutineScope(Dispatchers.IO).launch {
val res = service.getPostBySlug(slug)

try {
withContext(Dispatchers.Main) {

//Do something with response e.g show to the UI.
val post = res.body()!!.first()

UtilityMethods.hideView(loading_view)

val title = post.title?.rendered
val content = post.content?.rendered
val imageUrl = post.jetPackFeaturedMediaUrl

title_txtView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
Html.fromHtml(title, Html.FROM_HTML_MODE_COMPACT).toString()
else
Html.fromHtml(title).toString()

content_txtView.loadData(content.toString(), "text/html", "UTF-8")

Picasso.get().load(imageUrl).fit().centerCrop().into(thumbnail_imgview)
}

} catch (e: HttpException) {
UtilityMethods.showView(network_error_msg)
} catch (e: Throwable) {
Toast.makeText(this@PostContentActivity, "Ooops: Something else went wrong", Toast.LENGTH_LONG)
}
}
}

最佳答案

我的代码可以工作了,新代码是:

private fun handleIntent(slug: String) = GlobalScope.launch(Dispatchers.Main) {
val service = UtilityMethods.migrationTimeService()

UtilityMethods.showView(loading_view)
UtilityMethods.hideView(network_error_msg)

try {
val res = withContext(Dispatchers.IO) {
service.getPostBySlug(slug)
}

//Do something with response e.g show to the UI.
val post = res.body()!!.first()

UtilityMethods.hideView(loading_view)

val title = post.title?.rendered
val content = post.content?.rendered
val imageUrl = post.jetPackFeaturedMediaUrl

title_txtView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
Html.fromHtml(title, Html.FROM_HTML_MODE_COMPACT).toString()
else
Html.fromHtml(title).toString()

content_txtView.loadData(content.toString(), "text/html", "UTF-8")

Picasso.get().load(imageUrl).fit().centerCrop().into(thumbnail_imgview)
}
catch (e: HttpException) {
Toast.makeText(this@PostContentActivity, "Exception ${e.message}", Toast.LENGTH_LONG).show()
}catch (e: IOException) {
UtilityMethods.hideView(loading_view)
UtilityMethods.showView(network_error_msg)
} catch (e: Throwable) {
Toast.makeText(this@PostContentActivity, "Ooops: Something else went wrong ${e.message}", Toast.LENGTH_LONG).show()
}
}

关于android - 使用 kotlin 协程处理 retrofit 2.6 的无互联网连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56713483/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com