# android.os.NetworkOnMainThreadException

**Code:** `NetworkOnMainThreadException` · **Category:** Android · **Seen on:** Android

The app made a network call on the main (UI) thread, which Android forbids.

## Meaning

Network calls must run in a background thread — Kotlin coroutines with Dispatchers.IO, an Executor, WorkManager or a library like Retrofit with async calls/suspend functions.

## Common causes

- HttpURLConnection/OkHttp execute() called in an Activity/Fragment directly
- runBlocking on the main thread
- Synchronous SDK call in onCreate

## Quick fix

1. Move the call to Dispatchers.IO (viewModelScope.launch)
2. Use Retrofit suspend functions or enqueue()
3. Never use runBlocking on the main thread

## Detailed fix by platform

### Kotlin

1. 

```kotlin
viewModelScope.launch {
    val user = withContext(Dispatchers.IO) { api.getUser(id) }
    _state.value = user
}
```


## How to diagnose

1. **Stack** — Which call in onCreate/onClick?
2. **Threading** — Dispatcher used

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/android/networkonmainthreadexception)
