Is a good approach to save java collections when using onsaveInstanceState/onRestoreInstanceState
flow?
I have an activity that populates some information using some java collections (for example an ArrayList
containing objects of type A). This information is populated in a ListView
, like normal android applications do. Additionally, each row will start a detail activity for result (startActivityForResult(...)
) and is expected to do some updates when it returns (using onActivityResult).
For testing purposes, i enabled the "Don't keep activities" on the device developer preferences to see if the application crashes. Logically, when my parent activity is removed, all objects will be gone. When i return to that activity (onActivityResult
is executed) my list is empty/null.
My question is, is good approach to save my list in onSaveInstanceState
and restore is on onRestoreInstanceState
method in order to prevent empty lists or is enough to check if the list is null on onActivityResult
method? That will depend on my activities logic? Or it is good practice to save all items that will be used on onActivityResult
method?
Well if you don't do it your app crashes right? :)
I think it's a good approach to save all your objects with
onSaveInstanceState
becauseAndroid
will only restore yourViews
layout logic, not your data model logic, that's up to you. And don't forget that you are experiencing this inonActivityResult
but if your app goes to background let's say you receive a phone call, when you get back,onResume
will be called and your data model will be null at that point too. So the Activity life-cycleonSaveInstanceState
andonRestoreInstanceState
should always be implemented if you need to persist your data model. Of course it will depend on your logic because if you fetch all your data inonResume
you'll never have this issue.More here: onSaveInstanceState and onRestoreInstanceState
ps: your
Objects
need to implementSerializable
orParcelable