Search code examples
onsaveinstancestate

Android - Why the hell we should use saveInstanceState bundle in fragment and not fragment arguments?


I've just tested the behaviour of fragment's arguments bundle. It is persistent like saveInstanceState bundle! If I save something into fragment arguments it survives activity and even application killing! So why the hell is saveInstanceState bundle there? o_O

P.S. In activity intent's extras case, into which I added for example string inside activity code, doesn't survive even activity recreation. Survive only those put into while creation of intent itself. So it is comprehensible why we need saveInstanceState there.


Solution

  • Fragment arguments are meant to be used externally to initialize the fragment. Saved instance state is meant to be used internally by the fragment itself. There's also lifecycle implications. So the framework will call onSaveInstanceState() when appropriate, but if you're calling setArguments(), you really don't know when you should be calling it. Unless you call it during onSaveInstanceState(), in which case just use the saved state. If you're using arguments to store state data, there's a chance of corrupting the original init data. Finally, setArguments() can't be called after the fragment state has been saved, so this approach is limited as to when it will work.