简体   繁体   中英

OnSaveInstanceState/OnRestoreInstanceState with java collections

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 because Android will only restore your Views layout logic, not your data model logic, that's up to you. And don't forget that you are experiencing this in onActivityResult 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-cycle onSaveInstanceState and onRestoreInstanceState 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 in onResume you'll never have this issue.

More here: onSaveInstanceState and onRestoreInstanceState

ps: your Objects need to implement Serializable or Parcelable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM