FragmentPagerAdapter getItem is not called - android

I am not able to reuse fragment in FragmentPagerAdapter.. Using destroyItem() method, It is deleting the fragment but still does not called getItem() again..There are just 2-3 Images so I am using FragmentPagerAdapter Instead of FragmentStatePagerAdapter..
public class ExamplePagerAdapter extends FragmentPagerAdapter {
ArrayList < String > urls;
int size = 0;
public ExamplePagerAdapter(FragmentManager fm, ArrayList < String > res) {
super(fm);
urls = res;
size = urls.size();
}
#Override
public int getCount() {
if (urls == null) {
return 0;
} else {
return size;
}
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);
trans.commit();
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new FloorPlanFragment();
Bundle b = new Bundle();
b.putInt("p", position);
b.putString("image", urls.get(position));
Log.i("image", "" + urls.get(position));
fragment.setArguments(b);
return fragment;
}
}
And In FragmentActivity,
pager.setAdapter(new ExamplePagerAdapter(getSupportFragmentManager(), res2));

KISS Answer:
Simple use FragmentStatePagerAdapter instead of FragmentPagerAdapter.
I got the answer.. Firstly I thought to delete this question as I am doing a very silly mistake but this answer will help someone who is facing the same problem that Instead of FragmentPagerAdapter, use FragmentStatePagerAdapter.
As #BlackHatSamurai mentioned in the comment:
The reason this works is because FragmentStatePagerAdapter destroys
as Fragments that aren't being used. FragmentPagerAdapter does not.

Using a FragmentStatePagerAdapter didn't fully fix my problem which was a similar issue where onCreateView was not being called for child fragments in the view pager. I am actually nesting my FragmentPagerAdapter inside of another Fragment therefore the FragmentManager was shared throughout all of them and thus retaining instances of the old fragments. The fix was to instead feed an instance of the getChildFragmentManager to the constructor of the FragmentPagerAdapter in my host fragment. Something like...
FragmentPagerAdapter adapter = new FragmentPagerAdapter(getChildFragmentManager());
The getChildFragmentManager() method is accessible via a fragment and this worked for me because it returns a private FragmentManager for that fragment specifically for situations in which nesting fragments is needed.
Keep in mind however to use getChildFragmentManager() your minimum API version must be atleast 17 (4.2), so this may throw a wrench in your gears. Of course, if you are using fragments from the support library v4 you should be okay.

Override long getItemId (int position)
FragmentPagerAdapter caches the fragments it creates using getItem. I was facing the same issue- even after calling notifyDataSetChanged() getItem was not being called.
This is actually a feature and not a bug. You need to override getItemId so that you can correctly reuse your fragments. Since you are removing fragments, your positions are changing. As mentioned in the docs:
long getItemId (int position)
Return a unique identifier for the item at the given position.
The default implementation returns the given position. Subclasses should override this method if the positions of items can change.
Just provide a unique id to each fragment and you're done.
Using a FragementStatePagerAdapter or returning POSITION_NONE in int getItemPosition (Object object) is wrong. You will not get any caching.

I did what #kanika and #Jraco11 had posted but I still had the problem.
So, after a lot of changes, I found one that worked for me and was added to my FragmentPagerAdapter the next code:
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
According to what I read, getItemPosition is used to notify the ViewPager whether or not to refresh an item, and to avoid updates if the items at the visible positions haven't changed.

method getItem() is used only to create new items. Once they created, this method will not be called. If you need to get item that is currently in use by adapter, use this method:
pagerAdapter.instantiateItem(viewPager, TAB_POS)

There are two different scenarios :
1.) You have same layout for every pager :
In that case, it will be better if you'll extend your custom adapter
by PagerAdapter and return a single layout.
2.) You have different layout for every pager :
In that case, it will be better if you'll extend your custom adapter
by FragmentStatePagerAdapter and return different fragmets for every pager.

I found that setting a listener on the tab-layout stopped this from being called, probably because they only have space for one listener on tabLayout.setOnTabSelectedListener instead of an array of listeners.

Related

ViewPager with instant refresh android

I have a ViewPager and its child fragments are dynamic. I am using them in the same fragment class and I am changing the field's value dynamically. But when I changing the ViewPager position, It is not updating the fragment. I have to change the values instantly.
Thank you.
Declare refreshFragment method in your fragment class then
In ViewPagerAdapter class overwritte method
#Override
public int getItemPosition(#NonNull Object object) {
MyFragment f = (MyFragment ) object;
if (f != null) {
f.refreshFragment();
}
return super.getItemPosition(object);
}
When you call
viewPagerAdapter.notifyDataSetChanged();
it will call getItemPosition method in adapter class and update your fragment using refreshFragment method.
Android by default retains one page on both sides of the current page for optimised loading. Since you need the pages to refresh on every time, you need to use viewpager.setOffScreenPageLimit(0) to set all pages to be recreated every time they are viewed

Adding a page to ViewPager

Trying to programmatically add a fragment page to my ViewPager, I get:
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged!
Expected adapter item count: 3, found: 2
Pager id: com.my.app:id/view_pager
Pager class: class android.support.v4.view.ViewPager
Problematic adapter: class com.my.app.ui.BaseFragmentPagerAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:1000)
at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
at ...
I'm simply calling these few lines on my FragmentPagerAdapter implementation:
adapter.addFragment(new Fragment(), "FIRST");
adapter.addFragment(new Fragment(), "SECOND");
pager.setAdapter(adapter);
//later... (on click of a button)
adapter.addFragment(new Fragment(), "THIRD");
adapter.notifyDataSetChanged();
It actually adds the third page, but when I try to swipe there, it fails with the above mentioned exception. Until today I thought I had a pretty complete understanding of how adapters work. Now I can't figure out what's wrong.
From debugging, it seems that all the time adapter.getCount() correctly returns 3 (after adding the third page), but when I'm there to the third page it eventually returns 2 and breaks, as if someone called destroyItem() on it, but that's not me.
Here's my simple class:
public class BaseFragmentPagerAdapter extends FragmentPagerAdapter {
private SparseArray<Fragment> mFragments;
private ArrayList<String> mFragmentTitles;
public BaseFragmentPagerAdapter(FragmentManager manager) {
super(manager);
this.mFragments = new SparseArray<>();
this.mFragmentTitles = new ArrayList<>();
}
public void addFragment(Fragment f, String title) {
this.mFragments.append(mFragments.size() , f);
this.mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return this.mFragments == null ? null : this.mFragments.get(position) ;
}
#Override
public int getItemPosition(Object object) {
return this.mFragments.indexOfValue((Fragment) object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
this.mFragments.remove(position);
this.mFragmentTitles.remove(position);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
#Override
public int getCount() {
return mFragmentTitles.size();
}
}
Note that nothing changes if I use a FragmentStatePagerAdapter rather than FragmentPagerAdapter.
I will answer this myself since I found the answer while writing the question (as often). I'm not sure this is the best solution, but it worked.
Basically, when going to page 3, since it's not directly swipable-to, the adapter will call destroyItem() on page 1. Shouldn't FragmentPagerAdapter hold all items in memory without destroying them?
Well, I do hold fragments in memory through the mFragments fields. The call to destroyItem() destroys the associated view of the fragment, but should not destroy the fragment itself (I might be slightly wrong here, but you get the point).
So it's up to you (me) to keep the fragments in memory, and not invalidating them on destroyItem(). Specifically, I had to remove these two lines:
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
//removed: this.mFragments.remove(position);
//removed: this.mFragmentTitles.remove(position);
}
This way getCount() keeps returning correctly 3, and when you are back to page 1, the adapter can get its fragment through getItem().
Edit
After dealing with it for a day, I can say that, at a first glance, having a FragmentPagerAdapter that does not hold fragments in memory makes no sense to me.
It is documented that it should be used just for a few static fragments. ViewPager, by default, holds the current item, the one before and the one after, but you can tune this setting through viewPager.setOffscreenPageLimit().
If you destroy them during destroyItem(), things get bad. It will be easy to reinstantiate them through some logic in getItem(), but it is quite hard to save their instance state. For instance, onSaveInstanceState(Bundle outstate) is not called after destroyItem().
If your fragments are many and you want to accept the possibility that one of more get destroyed, you just switch to FragmentStatePagerAdapter, but that's another story: it automatically calls onSaveInstanceState and lets you retain what you need to retain.
Using FragmentPagerAdapter, thus renouncing on the state-saving features of FragmentStatePagerAdapter, makes no sense if you don't retain. I mean, either you retain the instances, or you save their state (as suggested in the comments). For the latter, though, I would go for FragmentStatePagerAdapter that makes it easy.
(Note: I'm not talking about retaining instances when the activity gets destroyed, but rather when a page of the ViewPager goes through destroyItem and the associated fragment goes through onDestroyView()).

Replace a fragment within a Viewpager(notifyDataSetChanged does not work)

My MainActivity contains a viewPager.
In the MainActivity.java, I set the adapter for viewpager. The adapter extends FragmentStatePagerAdapter. The fragment I want to replace is a
cameraFragment. So when the user clicks on the switch camera button, I want to now show the camera fragment, this time with a front camera on.
On clicking the switch Camera button, I remove the fragment from the arraylist of fragments I had passed to the custom adapter. I add the new fragment and call notifydatasetchanged. However, this does not result in the new fragment being added. How do I achieve dynamic replacement of fragments within a viewpager which is backed my a custom fragment state pager adapter?
Code :
mainPageFragments = new ArrayList<>();
mainPageFragments.add(new ResultsFragment_());
mainPageFragments.add(DemoCameraFragment_.newInstance(false));
pagerAdapter = new MainViewPagerAdapter(getSupportFragmentManager(),mainPageFragments);
To replace the fragment : On receiving the related event I do,
mainPageFragments.remove(1);
if (event.getCameraState().equals(CameraSwitchButton.CameraTypeEnum.BACK)) {
mainPageFragments.add(DemoCameraFragment.newInstance(false));
} else {
mainPageFragments.add(DemoCameraFragment.newInstance(true));
}
// Not Working...
pagerAdapter.notifyDataSetChanged();
Adapter Code :
public class MainViewPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> fragmentsArray;
public MainViewPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragmentsArray) {
super(fm);
this.fragmentsArray = fragmentsArray;
}
#Override
public Fragment getItem(int position) {
return fragmentsArray.get(position);
}
#Override
public int getCount() {
return fragmentsArray.size();
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
Your MainViewPagerAdapter.getItemPosition is the cause of your issue.
Default implementation always returns POSITION_UNCHANGED. For pager to remove your fragment you have to return PagerAdapter.POSITION_NONE for the fragments that are removed.
Additionally your current design contradicts with the idea of FragmentStatePagerAdapter. From the FragmentStatePagerAdapter documentation: "This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages."
Your current implementation holds all fragments in an array, and so defeats this mechanism. Correct implementation would be to create fragments in MainViewPagerAdapter.getItem method and let the adapter to handle fragments lifecycles as needed.
Thanks to #Okas. I made the following change to getItemPosition within my FragmentStatePagerAdapter subclass.
#Override
public int getItemPosition(Object object) {
if (object instanceof DemoCameraFragment_)
return POSITION_NONE;
return super.getItemPosition(object);
}
I added logs to the OnCreate of both my fragments to confirm if they were getting recreated or not. As per my requirement, only the second fragment is recreated.

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)
}

Swapping fragments in a viewpager

I have a ViewPager with 3 Fragments and my FragmentPagerAdapter:
private class test_pager extends FragmentPagerAdapter {
public test_pager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return fragments[i];
}
#Override
public long getItemId(int position) {
if (position == 1) {
long res = fragments[position].hashCode()+fragment1_state.hashCode();
Log.d(TAG, "getItemId for position 1: "+res);
return res;
} else
return fragments[position].hashCode();
}
#Override
public int getCount() {
return fragments[2] == null ? 2 : 3;
}
#Override
public int getItemPosition(Object object) {
Fragment fragment = (Fragment) object;
for (int i=0; i<3; i++)
if (fragment.equals(fragments[i])){
if (i==1) {
return 1; // not sure if that makes a difference
}
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
}
In one of the page (#1), I keep changing the fragment to be displayed. The way I remove the old fragment is like this:
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().remove(old_fragment1).commit();
And then just changing the value of fragments[1]
I found that I cannot really add or replace the new one or it will complain the ViewPager is trying to add it too with another tag... (am I doing something wrong here?)
All the fragments I display have setRetainInstance(true); in their onCreate function.
My problem is that this usually works well for the first few replacement, but then when I try to reuse a fragment, sometimes (I have not really figured out the pattern, the same fragment may be displayed several times before this happens) it will only show a blank page.
Here is what I have found happened in the callback functions of my Fragment I am trying to display when the problem happens:
onAttach is called (but at that time, getView is still null)
onCreateView is not called (that's expected)
onViewStateRestored is not called (why not?)
onResume is not called (I really thought it would...)
If it changes anything, I am using the support package, my activity is a SherlockFragmentActivity
EDIT (to answer Marco's comment):
The fragments are instantiated in the onCreate function of the Activity, I fill an ArrayList with those fragments:
char_tests = new ArrayList<Fragment>(Arrays.asList(
new FragmentOptionA(), new FragmentOptionB(), new FragmentOptionC()));
The I pick from that list to set fragments[1] (that's all done in the UI thread)
I fixed this by changing test_pager to extends FragmentStatePagerAdapter instead.
I am still confused as to what PagerAdapter should be used depending on the usage. The only thing I can find in the documentation says that FragmentPagerAdapter is better for smaller number of pages that would be kept in memory and FragmentPagerStateAdapter better for a larger number of pages where they would be destroyed and save memory...
When trying to do (fancy?) things with Fragments, I found FragmentStatePagerAdapter is better when pages are removed and re-inserted like in this case. And FragmentPagerAdapter is better when pages move position (see bug 37990)

Categories

Resources