Search code examples
androidorientationdynamic-memory-allocation

How do I save an ArrayList of Float objects so that I can retrieve it when my Activity restarts?


I have a question. What is the best way to store an ArrayList of Float objects so that I can I can reload the ArrayList when my Activity restarts due to switching my device's orientation? I thought about using Bundles, but then I would have had to extend the Float class to make it implement Parcelable. Since the class has been declared as final, unfortunately, I can't do that. I have done a bit of searching, and have come across a few solutions to similar problems, such as overriding onRetainNonConfigurationInstance(). I also thought about creating my own bare-bones wrapper class for a float primitive and making it Parcelable. It must be noted that the ArrayLists I wish to save are inside classes whose instances are created inside of my Activity's DrawView instance.

I didn't want to post any code yet because I haven't done anything to solve the problem other than researching possible solutions. If you guys need to see it, please let me know and I will gladly post it.

On a related note, the reason I decided to use ArrayLists was because I wanted to use some form of dynamic memory allocation. Since, due to the nature of my app, I cannot predict how many objects will be on the array, I wanted to have some way to only allocate as much memory as I need to store the Float objects. Truth be told I only need to store float primitives, but ArrayLists require non-primitives By any chance, due you guys know of a better way to do this, because using ArrayLists with Floats just to store primitive values seems a bit clunky to me.


Solution

  • The NonConfig approach is now (as of API 13/Android 3.2) deprecated, but that doesn't mean much in practice especially if you want to support older API levels, because deprecated methods usually stay for quite a long time. As of today, according to official Google figures, Android 2 aka APIs 8 to 10 has a market share of 43.8% (note: that page will get updated regularly) and many 2.3 (API 9 or 10) devices are being currently sold in the budget market segment. So think twice if you don't want to support these, and rest assured that Google won't disable the NonConfig methods any time soon.

    The nice part about onRetainNonConfigurationInstance() and getLastNonConfigurationInstance() is that they are extremely efficient both regarding resource consumption and implementation effort. With almost 50% of the devices out there not offering any better approach, it's simply the way to go as of today.