CalledFromWrongThreadException 🤖 Android

CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views

Background code updated a View directly; UI changes must happen on the main thread.

Seen on: Android

Meaning

Callbacks from network libraries, Executors or Dispatchers.IO run off the main thread. Switch back to Main (withContext(Dispatchers.Main), runOnUiThread, LiveData/StateFlow) before touching views.

Common causes

  • Updating views inside a background callback
  • Coroutine running on Dispatchers.IO touching UI
  • Timer/Thread callbacks

⚡ Quick fix

  1. Use withContext(Dispatchers.Main) or runOnUiThread
  2. Expose state via StateFlow/LiveData and observe it in the UI

Detailed fix by platform

Kotlin

  1. kotlin
    lifecycleScope.launch {
        val data = withContext(Dispatchers.IO) { repo.load() }
        textView.text = data.title   // back on Main
    }

How to diagnose

  1. Thread — Callback thread
  2. Code — Where the view is touched

🔧 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.