我要用
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/