Questions
ThreadBeginner3 min
What happens if you update UI from a background thread?
UI ThreadCalledFromWrongThreadException
Answer
The Short Answer
Your app crashes with a CalledFromWrongThreadException:
android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.
Why This Happens
Android's View system is not thread-safe. If multiple threads modify views simultaneously:
- UI could be in inconsistent state
- Drawing could be corrupted
- Race conditions everywhere
So Android enforces that only the main thread touches views.
Code That Crashes
Thread { val data = fetchDataFromNetwork() textView.text = data // 💥 CRASH! }.start()
The Check Mechanism
// Inside View's internal code void checkThread() { if (mThread != Thread.currentThread()) { throw new CalledFromWrongThreadException( "Only the original thread that created a view hierarchy can touch its views." ); } }
How to Fix
1. runOnUiThread()
Thread { val data = fetchData() runOnUiThread { textView.text = data // ✅ Safe } }.start()
2. Handler
val handler = Handler(Looper.getMainLooper()) Thread { val data = fetchData() handler.post { textView.text = data // ✅ Safe } }.start()
3. View.post()
Thread { val data = fetchData() textView.post { textView.text = data // ✅ Safe } }.start()
4. Coroutines (Best)
lifecycleScope.launch { val data = withContext(Dispatchers.IO) { fetchData() } textView.text = data // ✅ Safe, already on Main }
5. LiveData
// In ViewModel _liveData.postValue(data) // Thread-safe // In Activity (observes on main thread) liveData.observe(this) { textView.text = it }
Exception: Some Methods Are Thread-Safe
A few View methods can be called from any thread:
View.postInvalidate()View.postInvalidateDelayed()View.post()View.postDelayed()
These internally post to the main thread's Handler.
Key Takeaway
Always update UI from the main thread. Use the modern tools (Coroutines, LiveData) that handle this automatically.
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚