🔧 Error Fixes
· 1 min read

Android: NetworkOnMainThreadException — How to Fix It


NetworkOnMainThreadException means you’re making a network request on the main (UI) thread. Android blocks this because network calls can take seconds, freezing the UI.

Fix 1: Use coroutines (modern Kotlin)

// ❌ On main thread — crashes
val response = URL("https://api.example.com/data").readText()

// ✅ Use coroutines
lifecycleScope.launch {
    val response = withContext(Dispatchers.IO) {
        URL("https://api.example.com/data").readText()
    }
    // Update UI here (back on main thread)
    textView.text = response
}
interface ApiService {
    @GET("data")
    suspend fun getData(): Response<MyData>
}

// In your ViewModel
viewModelScope.launch {
    val data = apiService.getData()
}

Fix 3: Use OkHttp with enqueue

client.newCall(request).enqueue(object : Callback {
    override fun onResponse(call: Call, response: Response) {
        runOnUiThread { /* update UI */ }
    }
    override fun onFailure(call: Call, e: IOException) {
        runOnUiThread { /* show error */ }
    }
})

Rule

Never do network, database, or file I/O on the main thread. Always use coroutines, AsyncTask (deprecated), or callbacks.