when app starts dinamically add fragment instance (say, fragment1) content layout in transaction not added stack. fragment displays cached data has been passed means of newinstance(list<obj>) static method. in onsaveinstancestate() save data can display if fragment recreated.
now suppose don't recreate fragment. suppose replace second fragment, say, fragment2 (adding transaction stack time), perform 2 screen rotations, , press back. app pop stack , attempt display fragment1 again turn attempt display list<obj> null nullpointerexception thrown.
i understand because fragment1 instance has never been saved in first place, since wasn't in stack , neither on display when device rotated.
my question is, what's appropriate way of supporting screen rotations in case? save initial transaction in stack , make onbackpressed() verify getsupportfragmentmanager().getbackstackentrycount() >= 1 before popping stack (i don't want initial transaction popped because fragment1 initial screen) don't think correct approach. ideas?
if list not large, thing pass bundle in onsaveinstancestate , retrieve in onrestoreinstancestate. these methods should still called on destruction/recreation though fragment not in foreground. however, if data large or not serializable or parcelable, not option.
from docs:
if restarting activity requires recover large sets of data, re-establish network connection, or perform other intensive operations, full restart due configuration change might slow user experience. [...] in such situation, can alleviate burden of reinitializing activity retaining fragment when activity restarted due configuration change. fragment can contain references stateful objects want retain.
it sounds in case want retain fragment holds list<obj>. problem requires activity check of retained fragments create in oncreate see if of them exist, , you've expressed concerns maintainability in instance.
in last resort, declare intention handle orientation changes using android:configchanges parameter in android manifest. prevent activity (and associated fragments , members) being destroyed , recreated in orientation change, , instead system call onconfigurationchanged in activity. if not override onconfigurationchanged, nothing happen on orientation change except screen rotate. google discourages this, among other reasons, because it's code smell. resorting means not handling state changes well, , if activity destroyed while user looking @ else, state not preserved properly.
edit:
if fragment receives data through arguments bundle, call setarguments(), bundle "will retained across fragment destroy , creation."
Comments
Post a Comment