如何在Kotlin Android上正确使用URL [英] How to properly use the URL with Kotlin Android

查看:620
本文介绍了如何在Kotlin Android上正确使用URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用

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函数的程序包不存在.

How can I simply read a JSON from a URL link? The package of the async function doesn't exist.

推荐答案

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

Android doesn't allow accessing the internet from the main thread. The simplest way around this would be to open the URL on a background thread.

类似这样的东西:

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

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

Don't forget to register Internet permission in the Android Manifest file.

这篇关于如何在Kotlin Android上正确使用URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆