user3867175 user3867175 - 1 year ago 80
Android Question

Restoring instance variables in Android upon activity recreation

I have an Android project for which I am creating a custom tab view. I have structured the main

) in such a way that it has a tab bar at the bottom of the screen with a
above it. Each option on the tab creates a new
(relating to that option). Now, to prevent recreation of fragments each time an option is clicked, I store the fragment in an instance variable in the activity. So, when a tab option is clicked, I check if its fragment is already created, if it is not already created, I create and add it to the
(and hide any existing fragment), otherwise, I just hide the existing fragment (stored in an instance variable called
) and show the already created fragment that matches the clicked option.

Also when the
of the activity is called, I set the initial tab to be the home tab (one of the tabs).
This works great, except when the activity is recreated (due to orientation changes). Here, I think the instance variables (essentially pointers to already created fragments) loose their value and are set to null. This causes the home tab to be created and be overlayed on the restored view. I also know that you can save state using the bundle passed to
and restore it using
. But the bundle needs to contain data which is serialisable. However, these instance variables are merely pointers! How do I restore their values?

NOTE: this problem is solved below in a comment posted by me.


Answer Source

The answer to your problem is using the bundle for state restoration. Create a class in where you can put the variables and is serializable so you can put the its object to the bundle. Or you may also use SharedPreferences to store the instance variables' value in the phone storage. I hope you got idea from my weird answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download