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

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for Android "Only the original thread that created a view hierarchy can touch its views."

Android "Only the original thread that created a view hierarchy can touch its views." - Easy solutions 👀📱

Are you trying to update a TextView in your Android app, but getting an annoying exception that says "Only the original thread that created a view hierarchy can touch its views"? 🤔 Well, don't worry! We've got you covered with easy solutions to this common issue. Let's dive in! 💪

The Problem 😩

First, let's understand the problem. The Android UI toolkit is not thread-safe, which means that all UI-related updates should be done on the main UI thread (also known as the "UI thread" or "main thread"). When you try to update a view from a different thread, you'll encounter the dreaded "CalledFromWrongThreadException" exception. This exception is thrown to prevent potential synchronization issues and ensure UI consistency. 🚫🔄

The Solution ✅

There are a few different ways you can solve this problem and update your views from the UI thread. Let's explore the two main approaches:

1. Using runOnUiThread 🏃‍♀️

One simple way to update a view from a different thread is to use the runOnUiThread method provided by the Activity class. Here's how you can do it:

runOnUiThread(new Runnable() {
    public void run() {
        // Update your view here
        currentTime.setText(time);
    }
});

In this approach, you create a new Runnable that contains the code to update your view, and then pass it to the runOnUiThread method. This method ensures that the run method of your Runnable is executed on the UI thread.

2. Using Handler 🎈

Another approach is to use a Handler to post a Runnable to the UI thread's message queue. Here's an example:

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
    public void run() {
        // Update your view here
        currentTime.setText(time);
    }
});

In this approach, you create a new Handler that is associated with the UI thread's message queue. Then, you use the post method to add your Runnable to the message queue. The run method of your Runnable will be executed on the UI thread.

Putting It All Together 🔄🎛

Now that you know the solutions, let's go back to your specific issue. To update the TextView from the run method, you can use either of the following approaches:

runOnUiThread(new Runnable() {
    public void run() {
        String time = String.format("%d:%d",
            TimeUnit.MILLISECONDS.toMinutes(pos),
            TimeUnit.MILLISECONDS.toSeconds(pos),
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(
                    pos))
        );
        currentTime.setText(time);  
    }
});

or

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
    public void run() {
        String time = String.format("%d:%d",
            TimeUnit.MILLISECONDS.toMinutes(pos),
            TimeUnit.MILLISECONDS.toSeconds(pos),
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(
                    pos))
        );
        currentTime.setText(time);  
    }
});

Both approaches will ensure that the setText method is executed on the main UI thread, avoiding the "CalledFromWrongThreadException" exception. 🎉

Conclusion 🎉📝

Updating views from a different thread in Android can be a bit tricky, but with the right solutions, you can easily overcome this issue. Remember to either use runOnUiThread or Handler to ensure that your UI updates are performed on the main UI thread.

We hope this guide helped you solve the "Only the original thread that created a view hierarchy can touch its views" problem! If you have any other questions or face other tech challenges, let us know in the comments below. We're always here to help! 😊👍

Now, go ahead and update those views like a pro! 🚀💻

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my