I would like to know if there is a method to Save a Custom Class while rotating in an Android app. I want to save all instanced object called of the MatrixGame class...someone can help me?
Thanks
You should serialize your object. You can implement Parcelable
or implement Serializable
(Parcelable
is several times faster). Then you will be able to put it in a Bundle
in onSaveInstanceState
and restore it in onCreate
or onRestoreInstanceState
.
Also, you can serialize your object to String
, e.g. json string.
Another option would be to store your object in a database or a file. It depends on your needs.
If you don't want to recreate this object on screen rotation you can change the lifecycle of your Activity
by adding a configuration change flag in AndroidManifest.xml
. If we are talking about a Fragment
, you can call setRetainInstance(true)
to avoid fragment recreation on rotation.
Since the Fragment lifecycle is independent - when you're using a Fragment you can set it so it doesn't get destroyed upon configuration changes.
As you noticed, the Activity class gets destroyed and re-created when you rotate the app (or apply other configuration changes), if you want to persist the Activity state you can use sqlite and save whatever you need in the onPause()
method. Then in the onCreate()
method check the DB for last known state.
If you want to avoid saving the state "forever" (meaning, the user turns off the app and tomorrow when she turns it back on - you want to start fresh and not load the last known state) you can add a timestamp and set a threshold which, if passed, the data is considered stale and gets disregarded.
Two comments:
setRetainInstance(true)