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

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

G

Ben Jakuben
STAFF
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: