I am using a FragmentPagerAdapter with fragments. My problem is that when I call setCurrentItem, the OnCreateView method of the fragment that is being loaded is called twice. It is important to note however that the fragment is not recreated, it is simply resumed. I am desperate to find a solution that causes OnCreateView to only be called once.
I have taken a look at the following questions and some more, but none of them contain answers for my case:
Android oncreateview called twice
OnCreateView called multiple times / Working with ActionBar and Fragments
Fragment onCreateView and onActivityCreated called twice
Most questions I found do not concern FragmentViewPagers, making them mostly unhelpful.
I would be very grateful for any help!
I am using a FragmentPagerAdapter with fragments. My problem is that
when I call setCurrentItem, the OnCreateView method of the fragment
that is being loaded is called twice. It is important to note however
that the fragment is not recreated, it is simply resumed. I am
desperate to find a solution that causes OnCreateView to only be
called once.
It is not called twice. What you are experiencing is the default behavior of the ViewPager, which caches always at least one of its page (Fragment), depending of the value of setOffscreenPageLimit(int limit). So onCreateView is called once for each instance returned by getItem
Related
What fragment lifecycle methods (onCreate, onViewCreate, onStart) are called after you setup ViewPager with, say, 10 fragments and call setCurrentItem(9)?
Will there be any difference if you call setCurrentItem(i, false)?
What fragment lifecycle methods (onCreate, onViewCreate, onStart) are called after you setup ViewPager
Every lifecycle method you mentioned plus onAttach, onResume, and onActivityStarted are called. There is nothing about a ViewPager that affects that. Refer to this picture to see the Fragment lifecycle.
Will there be any difference if you call setCurrentItem(i, false)?
No, false does not affect the lifecycle. the only thing that false will do is transition immediately to the page instead of smoothly across the ViewPager.
The onPause, onStop, etc. methods may be called after you scroll out of view of a Fragment, but that was not part of your question. ..
I have been struggling to find out what the correct management of Fragments within a FragmentActivity with a ViewPager is. Before I go into details, a quick summary of the issue that I am facing is the following:
I have a FragmentActivity with a ViewPager. The ViewPager uses a custom, yet very simple FragmentPagerAdapter. Each Fragment within the ViewPager comprises of an ExpandableListView. I also have an action bar button called "Refresh". For now, let's assume that the ViewPager has only one Fragment. The activity is created, and the Fragment's ExpandableListView is populated (so far so good). When the Refresh button is clicked, the handling method within the FragmentActivity iterates over the list of Fragments that are assigned to the FragmentPagerAdapter and calls refresh() on each Fragment to populate its ListView. However, when the orientation of the device changes (e.g. from portrait to landscape), the Activity is recreated and so are the fragments. Clicking the Refresh button now will iterate over non-initialised Fragments.
I know that I am being quite vague, especially without sample code, but please bear with me. I have traced the problem and method calls as follows from the start of the application/activity:
FragmentActivity.onCreate()
FragmentActivity.setContentView()
FragmentActivity.createPagerFragments() <-- this creates an ArrayList of Fragments and assignes them to a new FragmentPagerAdapter which is in turn assigned to the ViewPager.
Fragment.onAttach()
Fragment.onCreate() <-- nothing special here, just calling the super method.
Fragment.onCreateView() <-- nothing special here either, just inflating the layout
Fragment.onActivityCreated() <-- nothing here either.
<< All good, orientation changes here >>
FragmentActivity.onCreate()
Fragment.onAttach()
Fragment.onCreate()
FragmentActivity.setContentView()
FragmentActivity.createPagerFragments()
Fragment.onCreateView()
Fragment.onActivityCreated()
<< Refresh button clicked >>
FragmentActivity.refresh() <-- iterates over the newly created Fragments from #13 (not these by Android!).
<< Crash: NullPointerException for mExpandableListView in Fragment. >>
So the problem, as I see it, is as follows:
When Android re-creates the FragmentActivity and its Views after a change of screen orientation (calls #9-15 above), it creates new Fragment objects with their state restored to what the original ones were. However, these ones appear to be completely managed by the FragmentManager, and not by the FragmentPagerAdapter. In contrast, when the FragmentPagerAdapter is re-created along with the Fragments in the activity's onCreate method (see call #13) the Fragments that get assigned to the adapter never have their Fragment.onCreate() or Fragment.onCreateView() methods called at all. So when the refresh() method is called (see #17) the method iterates over these Fragments that have not been initialised. Therefore, when they try to populate the ExpandableListView, the view's instance variable is NULL. This is to be expected as the instance variable is only assigned in the Fragment.onCreateView() method that never gets called on these Fragments.
So my question is: how does one properly make re-use of the re-recreated (by Android) Fragments after the screen orientation has changed in order to avoid creating new ones that don't get initialised? I need to have a valid reference to them, in order to call their refresh() method that populates them on-demand. Ideally, they should also be assigned to the FragmentPagerAdapter as well.
I hope I have been clear in describing the issue, and the reason that I have not provided sample code is because the problem (as can be seen) is not from the code itself but from a rather incorrect (seemigly) re-creation of Fragments rather than re-use. But if needed, I can give you sample code, I just through this way would be clearer.
Thank you!
It's lot to read, but after reading just introduction and the question and having experience with FragmentStatePagerAdapter, which is similar to FragmentPagerAdapter I can tell you that:
After rotation your adapter will AUTOMAGICALLY attach old fragments. So it seems that although activity creating adapter is being recreated, FragmentManager, which is global and it's instance preserve activity's recreation will detect that new FragmentStatePagerAdapter is combined with the same ViewPager and is asking for the same Fragments and will simply fetch them from Fragment's BackStack.
You as designer of Fragments can notice this behavior by continues invocation of Fragment.onAttach() and Fragment.onDetach(). When onAttach() occurs it's either creation of your Fragment or reusing it after rotation. You should be able to distinguish that Fragment was rotated with use of callback onRestoreRnstanceState().
You will see in your logs many onCreate() and other states logs simultaneously, because FragmentStatePagerAdapter always fetches/creates min 3 Fragments (except if you set that they are only 2 or 1), so also after screen rotation 3 fragments will be reattached from backstack.
I hope that it helped.
I believe that this question, about retrieving the current fragment from a ViewPager, will help you. As already pointed out, fragments are managed by the Fragment(State)PagerAdapter and NOT Activity's or Fragment's lifecycle.
The first time the activity is created, fragments are returned by the getItem method. This method is called only once per fragment, even if the activity gets recreated.
Subsequent times, the fragments are returned by the instantiateItem method. Most probably, this is the place, where you need to get hold of your fragments and call their refresh methods.
How about adding this to Activity Tag in your manifest:
android:configChanges="orientation"
or this for API 13 or higher
android:configChanges="orientation|screenSize"
so it won't recreate your fragments when it changes orientation..
My application contains two fragments.
My Android manifest file contains the following line:
"android:configChanges="orientation|screenSize"
which I need for the second fragment. I don't want its onCreateView() or other method to be called an orientation change.
But my first fragment needs onCreateView() to be called when orientation changes. Since the manifest file contains the above line, the onCreateView() method is not called. Can anyone help me in sorting out this to make onCreateView() to be called when orientation changes for specific fragment?
I believe setRetainInstance() is the function you need.
From documentation:
Control whether a fragment instance is retained across Activity
re-creation (such as from a configuration change). This can only be
used with fragments not in the back stack. If set, the fragment
lifecycle will be slightly different when an activity is recreated:
onDestroy() will not be called (but onDetach() still will be, because
the fragment is being detached from its current activity).
onCreate(Bundle) will not be called since the fragment is not being
re-created.
onAttach(Activity) and onActivityCreated(Bundle) will
still be called.
I'm trying to change the activity title from a fragment (in this case, it's an android.support.v4.app.Fragment). To this end, I save the activity in an attribute on the fragment when onAttach() is called on the fragment. According to the docs, onAttach() should be called before onCreateView(), which I'm using to request some data used to fill up the view. When I kick off the thread for the network retrieval, I want to indicate that in the title, so I'm trying to call this.activity.setTitle() from the Fragment. However, that keeps throwing a NullPointerException. What am I missing here?
You can access the Activity in a Fragment using getActivity(). It can be called safely as soon as onActivityCreated() was called on the Fragment. Before that, it might not be there or might not have been fully initialized yet.
If your thread starts before that, just note the fact somewhere in your Fragment and only change the title after onActivityCreated was called.
Nowadays you can call requiredActivity() too that return FragmentActivityobject and if fragment doesn't come from an Activity, method throws a IllegalStateException
I'm attempting to save a ListFragment subclass across an orientation change so I added setRetainInstance(true) to the end of my onCreate function. I added an onSaveInstanceState method to add all of it's data to a bundle, then added code into onActivityCreated to load that data back. Unfortunately, it wouldn't work.
When I added some debugging messages with the help of Log.d I discovered that not only was onSaveInstanceState not being called, but onCreate was (which the documentation seems to say shouldn't happen when retainInstance is true). Neither onCreate nor onActivityCreated have bundles with my data (unsuprisingly).
I'm guessing this may be a problem with compatibility library, though I don't have an android 3.0+ device to test this.
Any help is appreciated and I can post some code snippets if necessary, though I'm not doing anything complicated.
Update: onDestroy is not being called when I change orientation (which is how it should be), so it seems that some of setRetainInstance is working
I finally figured out what my problem was. It all came down to a single line I'd forgot to add. In my FragmentActivity subclass I'd overrode onSaveInstanceState, but I never called super.onSaveInstanceState. Apparently, unlike other methods whose parents I'd forgotten to call, onSaveInstanceState won't throw a runtime error when I forget to call the parent classes version of it, instead setRetainInstance just stops working. I hope this saves someone the headache I went through trying to solve this.
It seems, when you set setRetainInstance = true while both onSaveInstanceState() and onActivityCreated() are called, then Bundle will not be returned.
However, as the as the ListFragment is being retained, you can simply store its state into a field, and handle it inside onActivityCreated().
Bear in mind, the Activity will still be destroyed and recreated.