in my app I’m using one activity and two fragments. The app uses a layout with a container so the fragments are added via transactions. The first fragment contains a listview and the other fragment a detail view for the listview items.
Both fragments use setRetainInstance(true). The fragments are added via a replace transaction and addToBackStack(null) is set. The listfragment contains an instance variable which holds some infos for the list. Now I’m changing to detail and press back and the instance variable is null. I read about setRetainInstance and addToBackStack and removed addToBackStack, but even then the instance variable is null.
Does anyone know what I might be doing wrong?
regards,
Thomas
setRetainInstance(true)will tell theFragmentManagerto keep the fragment around when the containingActivityis killed and rebuilt for some reason. It doesn’t guarantee that theFragmentinstance will stick around after a transaction to add or replace. It sounds like your adapter is being garbage collected and you’re not creating a new one.A more generally easy solution would be to make a viewless
Fragmentto retain yourListAdapter. The way you do this is to create theFragment, set the retain instance to true, and returnnullin the methodonCreateView(). To add it, just calledaddFragment(Fragment, String)via theFragmentTransaction. You never remove or replace it, so it will always stay in memory for the length of the app. Screen rotations won’t kill it.Whenever your
ListFragmentis created, inonCreateView()get theFragmentManagerand use either the methodfindFragmentById()orFindFragmentByTag()to retrieve your retained fragment from memory. Then get the adapter from that fragment and set it as your adapter for the list.