Declan McKenna
Declan McKenna

Reputation: 4900

How do I pass a tree of objects into a bundle?

I have an app that consists mostly of one instance that is a tree of objects. Every time my phone sleeps or I switch app my app resets and all the data within this tree of objects is lost.

I first tried using onSaveInstanceState() but the savedinstancestate bundle would not allow me to pass on the instance of the object I needed. I tried to pass the object off as a parcel but the objects within my object could not be saved to the parcel.

Lastly I tried using getNonConfigurationInstance which didn't appears to work and I abandoned getting it to work when I looked up that it was depreciated. The alternative to it is for API11, I am using API7.

Any advice appreciated, I've read the documentation through but cannot find anything short of going through all my objects and saving each variables one by one to save my instance state.

Thanks

Upvotes: 0

Views: 146

Answers (1)

Fixpoint
Fixpoint

Reputation: 9870

  1. You should use getNonConfigurationInstance only in conjunction with onRetainNonConfigurationInstance, because the former retains the object and the latter saves it. Also, they work only for configuration changes — i.e., when activity is immediately recreated in the same process.

  2. If objects on your tree are simple, you can try putting it into a JSON format and then serializing/deserializing it. I have once done that to persist state of my controller hierarchy, worked great.

  3. You can put Bundles inside Bundles with putBundle(String key, Bundle value).

  4. You can put Parcelables inside Bundles with putParcelable(String key, Parcelable value).

Options 2, 3 and 4 will require you to write a recursive converter of your tree into/from either JSONObjects, Bundles or Parcelables.

Upvotes: 3

Related Questions