Android Development
Programming
Multithreading
View Hierarchy
Software Troubleshooting

Android "Only the original thread that created a view hierarchy can touch its views."

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In the development of Android applications, managing UI elements efficiently is critical to creating a smooth user experience. One common issue developers encounter in Android programming is the "Only the original thread that created a view hierarchy can touch its views." error. This pertains to one of Android's core principles regarding thread safety and the manipulation of user interface elements.

Understanding the Error

This error occurs when a thread other than the UI thread attempts to modify the properties of UI components. In Android, the UI thread (also known as the main thread) is responsible for drawing and manipulating the user interface. This design choice is enforced to prevent concurrency issues and to ensure that the UI remains responsive and stable.

Technical Explanation

Android UI components are not thread-safe. This means that they do not handle synchronization internally, which could lead to inconsistent states if accessed from multiple threads simultaneously. To safeguard against this, Android enforces that only the UI thread can manipulate UI elements.

Common Scenarios Leading to This Error

  • Background Thread Updates: Attempting to update UI elements from background threads after performing time-consuming tasks like network operations or heavy computations.
  • AsyncTask: In some cases, developers use AsyncTask and accidentally place UI update logic in the doInBackground method instead of onPostExecute or onProgressUpdate, which run on the UI thread.
  • Threads or Timers: Using Java Thread or Timer to try to update UI components directly from their execution blocks.

How to Handle UI Updates Properly

  • Use runOnUiThread: This method is available in Activity class. It allows you to run your code on the UI thread from another thread:
java
1  runOnUiThread(new Runnable() {
2      public void run() {
3          // Update UI elements here.
4      }
5  });
  • Using View.post() Method: If you have access to a view, you can use the post method of the view to ensure the runnable you pass it is executed on the UI thread.
java
1  myView.post(new Runnable() {
2      public void run() {
3          // Update the view and other UI elements here.
4      }
5  });
  • Use Handler: Handlers are bound to the thread they are created from and you can use them to enqueue actions to be performed on that thread.
java
1  Handler handler = new Handler(Looper.getMainLooper());
2  handler.post(new Runnable() {
3      public void run() {
4          // UI update code here
5      }
6  });

Best Practices and Tips

  1. Long Running Tasks: Always use background threads for long-running tasks. Ensure any resulting UI updates are redirected back to the UI thread through the correct mechanisms.
  2. Tool Use: Tools like Android Lint and StrictMode can help identify accidental disk or network access on the application's main thread.
  3. Understanding Looper and Handler: Having a solid understanding of how Looper and Handler work can be beneficial for efficient and effective Android programming.

Summary Table

ConceptDescription
UI ThreadMain thread responsible for handling UI in Android.
Thread SafetyNeeds to keep UI components safe from concurrent access.
HandlersObjects used to schedule messages and runnables to be executed at some point in the future.
runOnUiThreadActivity method to execute code on the UI thread.
View.post()Method to ensure that the runnable is executed in the view's thread context.

Conclusion

Understanding threading in Android is crucial for building robust and responsive applications. The rule that only the UI thread may touch its views simplifies troubleshooting and debugging because it centralizes the interaction with UI components. By adhering to the practices outlined above, developers can avoid common pitfalls related to threading in Android.


Course illustration
Course illustration

All Rights Reserved.