How do you fix NetworkOnMainThreadException in Android?

← Android answers

Run the network call off the main thread, for example in a coroutine with withContext(Dispatchers.IO), then update the UI back on the main thread.

class UserViewModel(private val api: Api) : ViewModel() {
    val name = MutableLiveData<String>()
 
    fun load() {
        viewModelScope.launch {
            val user = withContext(Dispatchers.IO) { api.fetchUser() }
            name.value = user.name        // back on the main thread
        }
    }
}

Retrofit's suspend functions and OkHttp's enqueue already run off the main thread, so you only hit this exception with blocking calls such as HttpURLConnection or execute(). Disk and database access on the main thread causes dropped frames and strict-mode violations in the same way.

Do not turn off StrictMode or permit network access on the main thread to make the error go away; it only hides freezes your users will feel.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required