Programming Errors & Bugs
Open
Example from the ReviewMyCodes team
Android app crashes with NetworkOnMainThreadException when loading data
Description
My Kotlin Android app crashes as soon as the main screen tries to download JSON.
— This is an example problem from the ReviewMyCodes team, showing how a good question looks. Real community questions appear alongside it.
Expected
The data should load in the background and update the screen.
Actual
android.os.NetworkOnMainThreadException at java.net.URL.openStream
Steps to reproduce
- Launch the app
- App crashes on the main screen
Code
kotlin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val json = URL("https://api.example.com/items").readText()
showItems(json)
}