---
title: "How do you fix NetworkOnMainThreadException in Android?"
description: "Android forbids network calls on the main thread. Move the request to a coroutine on Dispatchers.IO, an executor, or a library that handles threading."
url: "https://bugsee.com/answers/android/fix-network-on-main-thread-exception/"
---

# How do you fix NetworkOnMainThreadException in Android?

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.

```kotlin
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

- [How do you fix "lateinit property has not been initialized" in Kotlin?](https://bugsee.com/answers/android/fix-lateinit-property-not-initialized/)
