Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Threads and Services Threads in Android The Problem with Threads

Chris Reeder
Chris Reeder
3,205 Points

So I created a Thread class and then tried to send a toast to my main activity using runonUiThread but I'm getting a sta

So I created a Thread class and then tried to send a toast to my main activity using runonUiThread but I'm getting a static error. I was going to set and and run multiple threads to do different things and then update the loading bar as they complete before finally starting a new activity.

Do I need a handler for the main UI thread? I wanted to store the method to update the loading bar in the main activity too, is that a problem?

(The error indicates 'this' in the Toast line is the problem)

1 Answer

Seth Kroger
Seth Kroger
56,405 Points

For a Toast, it requires a Context, and that is usually the Activity of the app. Thread doesn't inherit from Activity however, so 'this' in a Thread isn't the correct type to pass it. You should store a reference to the Activity inside the Thread and use that. (If the thread is an inner class of the activity you would also use MyActivtyClass.this to say you want the outer class' this)