Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Switching orientation with threads

I have an app that runs a threads in the background of just about every view. When the user switches the orientation, the view loads again and the thread post back to the old view that isn't there anymore. How do I take care of this problem? How do I make the thread post to the most recent main view? iOS doesn't do this :P

2 Answers


Ben Jakuben
Ben Jakuben
Treehouse Teacher

When you switch orientation in Android, the Activity is destroyed and created again, so onCreate() runs again. It's kind of a pain. You need to be careful to not start those background threads a second time.

Now, for the running background threads, one trick is to use a Fragment inside the Activity that you can retain and reuse even if the parent Activity is destroyed. Here's an article that talks about it with sample code: http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

By default, Fragments are destroyed and recreated along with their parent Activities when a configuration change occurs. Calling Fragment#setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle, signaling the system to retain the current instance of the fragment when the activity is recreated. As we will see, this will prove to be extremely useful with Fragments that hold objects like running Threads, AsyncTasks, Sockets, etc.

Great tutorial! I guess I'm a little confused on the onAttach function. I get an error when that function is called. I'm using SherlockFragmentActivity with ActionBar tabs. My tabs of course are Fragments. I created the non UI fragment to hold the instance of one of my fragments just like the tutorial says but I get that runtime error. I also tried the onAttachFragment but I get more errors so I guess I don't understand what's going on there.

Ben Jakuben
Ben Jakuben
Treehouse Teacher

Would you want to paste some code in? I (or maybe other students) can try troubleshooting it with you. :smile: