如何正确使用Kotlin Android的URL

问题描述 投票:1回答:2

我想用

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 EXCEPTION: main
    Process: com.mypackage.randompackage, PID: 812
    java.lang.RuntimeException: Unable to start activity ComponentInfo{ ***.MainActivity}: android.os.NetworkOnMainThreadException

如何从URL链接中简单地读取JSON? async函数的包不存在。

android kotlin kotlin-android-extensions kotlin-extension
2个回答
5
投票

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

像这样的东西:

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

不要忘记在Android Manifest文件中注册Internet权限。


1
投票

您可以使用协同程序:

val json = async(UI) {
        URL("https://my-api-url.com/something").readText()
    }

记得向build.gradle添加协同程序:

kotlin {
experimental {
        coroutines "enable"
    }
}
...
dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinx_coroutines_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlinx_coroutines_version"
...
}

Coroutines很棒。

© www.soinside.com 2019 - 2024. All rights reserved.