android - 如何在 Kotlin Android 中正确使用 URL

标签 android kotlin kotlin-android-extensions kotlin-extension

我要用

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

    val json = URL("https://my-api-url.com/something").readText()
    simpleTextView.setText(json)
}

但是出现了这个 fatal error

FATAL EXCEPTION: main
    Process: com.mypackage.randompackage, PID: 812
    java.lang.RuntimeException: Unable to start activity ComponentInfo{ ***.MainActivity}: android.os.NetworkOnMainThreadException

我怎样才能简单地从 URL 链接中读取 JSON? async 函数的包不存在。

最佳答案

Android 不允许从主线程访问互联网。 解决此问题的最简单方法是在后台线程上打开 URL。

像这样:

Executors.newSingleThreadExecutor().execute({
            val json = URL("https://my-api-url.com/something").readText()
            simpleTextView.post { simpleTextView.text = json }
        })

不要忘记在 Android list 文件中注册互联网权限。

关于android - 如何在 Kotlin Android 中正确使用 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47971972/

相关文章:

Android 使用 Zxing 生成二维码和条形码

android - 如何以编程方式检测用户何时在android中打开/关闭对讲

android - Crashlytics:查看所有 session 不显示所有自定义键

android - 在Kotlin中对单个列表进行分组和排序的更好方法

android - 如何使用 kotlin 从列表的第一个元素中获取第一个 Char?

android - 在自定义 ListView 适配器中按下项目时突出显示效果

android - 使用 Kotlin 在 fragment 中引用 RecyclerView 时出现空指针错误

android - Kotlin 向我解释了 Backing Fields

kotlin - 有没有办法像 shell 脚本一样在 adb shell 中运行 kotlin 脚本?

java.lang.NoClassDefFoundError : Failed resolution of: Ljava/lang/invoke/MethodHandles$Lookup 错误