Rod*_*Rod 1 android kotlin kotlin-extension kotlin-android-extensions
我想用
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)
}
Run Code Online (Sandbox Code Playgroud)
但是发生致命错误
FATAL EXCEPTION: main
Process: com.mypackage.randompackage, PID: 812
java.lang.RuntimeException: Unable to start activity ComponentInfo{ ***.MainActivity}: android.os.NetworkOnMainThreadException
Run Code Online (Sandbox Code Playgroud)
如何简单地从URL链接读取JSON?该async功能的软件包不存在。
Android不允许从主线程访问互联网。解决此问题的最简单方法是在后台线程上打开URL。
像这样:
Executors.newSingleThreadExecutor().execute({
val json = URL("https://my-api-url.com/something").readText()
simpleTextView.post { simpleTextView.text = json }
})
Run Code Online (Sandbox Code Playgroud)
不要忘记在Android Manifest文件中注册Internet权限。
| 归档时间: |
|
| 查看次数: |
3445 次 |
| 最近记录: |