NetworkOnMainThreadException 🤖 Android

android.os.NetworkOnMainThreadException

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

Seen on: Android

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

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.