ViewPager - FragmentStatePagerAdapter and handling rotation - android

I have a ViewPager which holds Fragments. ViewPager has an adapter of FragmentStatePagerAdapter
Adapter's getItem method.
#Override
public Fragment getItem(int position) {
String text= dbHelper.getText(position);
CustomFragment frg = new CustomFragment(text);
return frg;
}
I am initializing the fragment in the getItem method of the adapter.
Everything works perfectly.
When the orientation changes however, instead of restoring my initialized fragments, CustomFragments are created using the default constructor of CustomFragment. So this creates fragments with dummy data.
What is the reason of this?
How can i restore the previously created fragments?

The ideal way to initialise your Fragments is to create a factory method like:
public static CustomFragment newInstance(String text) {
Bundle arguments = new Bundle();
arguments.put("someText", text);
CustomFragment fragment = new CustomFragment();
fragment.setArguments(arguments);
return fragment;
}
and get the arguments with getArguments() in the onCreate() method and process it to initialise whatever you want in the fragment.
This way when your fragments are recreated on configuration change, the arguments are persisted and the Fragments take care of themselves when their onCreate() method is called.
You might have noticed the lint warnings about the same if you are using the latest tools.

Related

Passing arguments bundle to Fragment

I need to pass some variable from activity to fragment inside a tab layout. I found there are 2 preferred ways of passing argument bundles to the fragment by its initialization methods for the tab layout.
By creating static newInstance() method and providing details.
Creating instance of fragment inside FragmentPagerAdapter
But, I have some doubts how this works.
If I create this this is:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
MyFragment myFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
myFragment = new MyFragment();
Bundle args = new Bundle();
args.putString("id", id);
myFragment.setArguments(args);
}
// ...
}
Here I am creating the instance of fragment and setting its argument afterwords.
And if I create it in newInstance() method something like this:
public static MyFragment newInstance(String id) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putString("id", id);
myFragment.setArguments(args);
return myFragment;
}
Some doubts:
When will the onCreate() or onCreateView() will be called? What if after line new MyFragment() and before setting bundle?
Is there any possibility where getArguments can return null?
In both ways I am doing the same thing. Setting args after new MyFragment() call. How late I can set the arguemnts. Is it necessary to set arguments exactly after the new MyFragment() call?
Sorry, if I asked some silly question. But I am new to Fragments. Thanks :)
onCreate() and onCreateView() will be called sometime after you've committed the fragment transaction. i.e. called commit(). And you set bundle before that.
As long as you're setting bundle before commit, getArguments shouldn't be null.
Both are doing the same thing. In 1st you're creating the fragment instance by yourself and setting bundle yourself. In 2nd you're using what is called a factory method (Effective Java Item 2) which is managed by your fragment. So it's difficult to make mistake in 2nd as arguments are always set.

Fragment how to enter onCreateView lifecycle method

I want to create a new instance of a Fragment in a PagerAdapter with some method like Fragment1.newInstance(0);
but this does not enter the Fragment onCreateView method, where I want to take its layout... How can I make it enter the lifecycle method?
EDIT: For the swipe tabs I am using an external library, that extends PagerAdapter, maybe thats the problem?
Everything you need is described here. See section "Adding a fragment to an activity" especially to solve your problem.
This is because ViewPager doesn't recreate fragment on each swipe .. it creates fragment only once and keeps in memory and recreate once after it goes offScreenpageLimit() ...For recreating fragment each time you swipe ,you have to set
mViewPager.setOffscreenPageLimit(0);
But this method is not recommended if you have so many pages in viewpager (atleast more than 10)..
in your pager adapter class return the instance like this
#Override
public Fragment getItem(int position){
return Fragment1.newInstance(position);
}
And in your Fragment create a static instance like this
public static NearbyOffersFragment newInstance(int position) {
Fragment1 f = new Fragment1();
Bundle b = new Bundle();
b.putInt("position", position);
f.setArguments(b);
return f;
}
and onCreate of your fragment retrieve the postion
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt("position");
}

Android ViewPager and Fragment serialization

I've an activity with two attributes:
private Fragment firstFragment;
private Fragment secondFragment;
In onCreate method:
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
pager.setOffscreenPageLimit(6);
pager.setSaveEnabled(true);
where MyPagerAdapter extends FragmentStatePagerAdapter class.
Into getItem() method:
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
switch (position) {
case FIRST:
secondFragment = new FirstFragment();
secondFragment.setArguments(args);
return secondFragment;
case SECOND:
secondFragment = new SecondFragment();
secondFragment.setArguments(args);
return secondFragment;
}
}
and all works correctly.
But, when I change the screen orientation, the private attributes is set to null and I lost the reference of two fragments.
So i've tried to serialized this fragment with:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, FirstFragment.class.getName(), firstFragment);
getSupportFragmentManager().putFragment(outState, SecondFragment.class.getName(), secondFragment);
}
and load them into onCreate method with:
if (savedInstanceState != null) {
firstFragment = (FirstFragment) getSupportFragmentManager().getFragment(savedInstanceState, FirstFragment.class.getName());
secondFragment = (SecondFragment) getSupportFragmentManager().getFragment(savedInstanceState, SecondFragment.class.getName());
}
My questions:
1. Is it the correct way to serialized fragment into activity screen orientation changes?
2. Sometimes I've the error: "Unmarshalling unknown type code 55 at offset 448", is it possible that it has caused by fragment serialization?"
EDIT:
I need to have the fragments as activity attributes because I've a listener interface into activity that:
#Override
public void executeTask(String what) {
secondFragment.executeTask(what);
}
this method was invoked into firstFragment. So the FirstFragment can execute a method of SecondFragment.
I'm not sure what may be the cause of the problem but I'll give you a hint that may help.
I don't think that you should reference the Fragments in the Adapter from the Activity.
Mainly due to the fact that it's pretty hard to synchronize the Activity life-cycle, Fragment lifecycle and ViewPager children life-cycles. And if any bugs emerge the debugging can be really painful.
Believe me, been there, done that...
By the way - is there a reason why you need references to Fragments in your Activity ?
EDIT
I don't think you should pass the information between the Fragments this way. In general the FragmentManager handles (creates, deletes) Fragments on it's own and you cannot be sure that these Fragments will be available at any time.
I think that the best way would be to move your data to separate model (database entry, SharedPreference or a singelton class) and then letting know the Adapter that data has changed (by a DataObserver in Fragments or simply notify the Adapter to update children data by calling notifyDataChanged).
EXAMPLE
FragmentA --->listener (reloadData())--->Activity--->adapter.notifyDataChanged()-----> fragmentB gets updated
This way if you ever want to add a ThirdFragment or in fact any number of Fragments that will use the Data you will not have to worry about updating data in any of these - just let the Adapter worry about it.
If your using same layout for portrait and landscape then When orientation change you can avoid activity recreate. change your manifest as...
<activity android:name=".activity.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
and then override onConfigurationChanged() in activity ...
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
}

Navigating back to FragmentPagerAdapter -> fragments are empty

I have a Fragment (I'll call it pagerFragment) that is added to the backstack and is visible. It holds a viewPager with a FragmentPagerAdapter. The FragmentPagerAdapter holds (let's say) two fragments: A and B.
First adding of the fragments works great.
Fragment A has a button that once clicked, adds a fragment (C) to the backstack.
The problem is this: if I add that fragment (C), and then click back, the pagerAdapter is empty, and I cannot see any fragments inside.
If I use a hack, and destroy the children fragments (A and B) in the pagerFragments onDestroyView(), this solves the problem, although I don't wan't to use this hack.
Any ideas what the issue could be?
I had the same problem. The solution for me was simple:
in onCreateView I had:
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity()
.getSupportFragmentManager());
where SectionPageAdapter is something like this:
class SectionsPagerAdapter extends FragmentPagerAdapter {
...
}
after changing getSupportFragmentManager to
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
it started working!
It sounds like you are using nested fragments since your ViewPager is inside a PagerFragment. Have you passed getChildFragmentManager() to the constructor of your FragmentPagerAdapter? If not you should.
I don't think you need a FragmentStatePagerAdapter, but I would give that a shot since it handles saving and restoring Fragment state. The fact that your onDestroyView() hack works makes me think that you may want a FragmentStatePagerAdapter.
It could also have something to do with the way the FragmentPagerAdapter adds Fragments. The FragmentPagerAdapter doesn't add Fragments to the backstack. Imagine if you had a 10+ pages added in your ViewPager and the user swiped through them. The user would need to hit back 11 times just to back out of the app.
It may also be related to this post: Nested Fragments and The Back Stack.
Also I'm not sure what you are adding the Fragment C to. Are you adding it to the same container as the ViewPager?
Well at least you have a few options to investigate. In these situations I like to debug down into the Android SDK source code and see what's causing the behaviour. I recommend grabbing the AOSP source and adding frameworks/support and frameworks/base as your SDK sources. That's the only true way to understand what is happening and avoid making random changes until things work.
Use getChildFragmentManager() instead of getSupportFragmentManager().
It will work fine.
I just faced the problem in our project as well. The root cause is the way the the FragmentPagerAdapter works:
The FragmentPagerAdapter just detaches a Fragment he does not currently need from its View but does not remove it from its FragmentManager. When he wants to display the Fragment again he looks if the FragmentManager still contains the Fragment using a tag that is created from the view id of the ViewPager and the id returned by the adapters getItemId(position) call. If he finds a Fragment he just schedules an attach of the Fragment to its View within the updating transaction of the FragmentManager. Only if he does not find a Fragment this way he creates a new one using the adapters getItem(position) call!
The problem with a Fragment containing a ViewPager with a FragmentPagerAdapter is, that the contents of the FragmentManager is never cleaned up when the containing Fragment is put to the back stack. If the containing Fragment comes back from the back stack it creates a new View but the FragmentManager still contains the fragments that were attached to the old view and the attach of an existing fragment does not work anymore.
The easiest way to get rid of this problem is to avoid nested fragments. :)
The second easiest way is as already mentioned in other posts to use the ChildFragmentManager for the FragmentPagerAdapter as this one gets properly updated during the life cycle of the container fragment.
As there are projects (as my current one) where both options are not possible, I have published here a solution that works with an arbitrary FragmentManager by using the hashCode of the sub fragments as the item id of the fragment at that position. It comes at the price of storing all fragments for all positions within the adapter.
public class MyPagerAdapter extends FragmentPagerAdapter {
private static int COUNT = ...;
private final FragmentManager fragmentManager;
private Fragment[] subFragments = new Fragment[COUNT];
private FragmentTransaction cleanupTransaction;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
this.fragmentManager = fragmentManager;
}
#Override
public Fragment getItem(int position) {
return getSubFragmentAtPosition(position);
}
#Override
public int getCount() {
return COUNT;
}
#Override
public long getItemId(int position) {
return getSubFragmentAtPosition(position).hashCode();
}
//The next three methods are needed to remove fragments no longer used from the fragment manager
#Override
public void startUpdate(ViewGroup container) {
super.startUpdate(container);
cleanupTransaction = fragmentManager.beginTransaction();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
cleanupTransaction.remove((Fragment) object);
}
#Override
public void finishUpdate(ViewGroup container) {
super.finishUpdate(container);
cleanupTransaction.commit();
}
private Fragment getSubFragmentAtPosition(int position){
if (subFragments[position] == null){
subFragments[position] = ...;
}
return subFragments[position];
}
}
I had same problem, just set adapter twice at once and that's all.
Example code :
private fun displayImg(photo1:String, photo2:String){
val pager:ViewPager = v?.findViewById(R.id.ProductImgPager)!!
val arr = ArrayList<String>()
arr.add(photo1)
arr.add(photo2)
pager.adapter = AdapterImageView(fm, arr ,arr.size)
pager.adapter = AdapterImageView(fm, arr ,arr.size)
}

How to call some method for Fragment which is in FragmentPagerAdapter?

I have following issue. I have ViewPager and FragmentPagerAdapter for it.
All I need to do is call some method from my Fragment which is in ViewPager when this page was selected.
I tried to keep all my Fragments in List inside my adapter, but the problem is that when I rotate my device Adapter use previous fragments. New fragments were created after rotation and I have list of them, but I don't now how to get access to previous fragments. I have references to new fragments only.
Here is my adapter:
public class MainPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmentList;
public MainPagerAdapter(FragmentManager fm) {
super(fm);
fragmentList = new ArrayList<Fragment>();
fragmentList.add(new TaskPageFragment());
fragmentList.add(new HistoryFragment());
fragmentList.add(new TestFragment());
}
#Override
public Fragment getItem(int i) {
return fragmentList.get(i);
}
#Override
public int getCount() {
return 3;
}
}
Of course when I trying to access to fragment which was only created like an object, I can't get access to Activity Context.
Fragment fragment = pagerAdapter.getItem(i);
if (fragment instanceof SelectionListener) {
((SelectionListener)fragment).onTabSelected();
}
Here is onTabSelected() method call is shown. It's my interface which I implemented to each fragment in ViewPager and when it gets called after screen rotation I get null Context
Device configurations can change during runtime (such as screen orientation). When this happens the Activity is restarted. This is done so your activities can adjust to match the new device configuration, and since fragments are within Activities they are also 'destroyed'.
However your issue may be solved with something simple, since from what I understand from your question you are not looking for UI configuration changes and assuming you are using API 11+.
public void setRetainInstance (boolean retain)
Since: API Level 11
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.
public MainPagerAdapter(FragmentManager fm) {
Fragment frag = null;
super(fm);
fragmentList = new ArrayList<Fragment>();
frag = new TaskPageFragment();
frag.setRetainInstance(true);
fragmentList.add(frag);
frag = new HistoryFragment();
frag.setRetainInstance(true);
fragmentList.add(frag);
frag = new TestFragment();
frag.setRetainInstance(true);
fragmentList.add(frag);
}

Categories

Resources