ViewPager getItemPosition() never called. Who should call it? - android

I am a bit puzzled about the Fragment[State]PagerAdapter. Basically my issue is that I need to change the content (Fragments) of a ViewPager depending on screen orientation. I read a number of posts on this and some say I should override getItemPosition(Object) from PagerAdapter. I have done this but the method is never called, and I can't find any call to it in PagerAdapter, FragmentPagerAdapter nor FragmentStatePagerAdapter. Anyone out there know how this works and mind explaining?
Currently I made an ugly hack in my instantiateItem() to test a theory of mine, but this is nothing I really want to use. As you can see I remove the fragment if getItemPosition() return POSITION_NONE. In getItemPosition() I have some logic to determind if a fragment should still be in the pager or not.
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Hack since getItemPosition is never called.
final long itemId = getItemId(position);
String name = makeFragmentName(container.getId(), itemId);
Fragment fragment = mFragmentManager.findFragmentByTag(name);
if(fragment != null && getItemPosition(fragment) == POSITION_NONE) {
mFragmentManager.beginTransaction().remove(fragment).commit();
mFragmentManager.executePendingTransactions();
}
fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
JavaDoc says:
public int getItemPosition(Object object)
Called when the host view is attempting to determine if an item's position
has changed. Returns POSITION_UNCHANGED if the position of the given
item has not changed or POSITION_NONE if the item is no longer present
in the adapter.
The default implementation assumes that items will never
change position and always returns POSITION_UNCHANGED.
#param object Object representing an item, previously returned by a call to
instantiateItem(View, int).
#return object's new position index from [0, getCount()),
POSITION_UNCHANGED if the object's position has not changed,
POSITION_NONE if the item is no longer present.
I have tested my code on API level 19 and 22 and the issue is the same.
Thanks in advance.
EDIT: I extend FragmentStatePagerAdapter or FragmentPagerAdapter. If I extend PagerAdapter and wrote me own instantiate and destroy methods I might be able to workaround this. Was hoping I would not have too though. Plus it's annoying to not understand it. ;)

getItemPosition() is only called after a notifyDataSetChanged() call.
So first, modify your data set and then make a notifyDataSetChanged() call.
You will also have to override getItemId() to return a static identifier. By default it returns the position given.

getItemPosition() is called after notifyDataSetChanged() is called on the adapter. That's like saying you want to change which fragments are in the ViewPager.
For your case, if you're making changes on screen orientation, the entire activity is probably being taken down and rebuilt, so it's just a matter of having the adapter do the right thing. In very simplistic terms:
#Override
public Object instantiateItem(ViewGroup container, int position) {
if (orientation == ORIENTATION_PORTRAIT) {
// ... set up the views for portrait
} else {
// ... set up the views for landscape
}
}

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

onPageSelected runs BEFORE onCreateView is called?

I'm using a ViewPager to cycle through a set of fragments, and I want to update each fragment after it slides onto the screen. Basically, I want the text to "fade in" after the fragment has settled.
I tried using the fragment's onStart and onResume methods, and while this works for most of the pages, it does NOT work for the second page, because for whatever dumb reason, the first page AND the second page have their onStart/onResume methods called at the same time (before the second page ever hits the screen).
Now I'm trying to get it to work with the onPageChangeListener's onPageSelected callback. That method looks like this:
#Override
public void onPageSelected(final int position) {
mCurrentPosition = position;
PageFragment fragment = (PageFragment) ((MainActivity.ScreenSlidePagerAdapter) mViewPager.getAdapter()).getItem(position);
fragment.onSelect();
}
And the onSelect method in the fragment looks like this:
public void onSelect(){
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
mSwitcher.setText("");
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
Media currentMedia = slideshow.getMedia().get(mNum);
mSwitcher.setText(currentMedia.getDisplayName());
}
},
4000);
}
The problem with this way is that the line mSwitcher.setText(""); throws a NullPointerException
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextSwitcher.setText(java.lang.CharSequence)' on a null object reference
Which would suggest that the onCreateView method in that class has yet to run since that's where the mSwitcher variable is instantiated. Which seems bananas to me, since the view is already sliding onto the screen at this point.
Any ideas about how to solve this problem would be greatly appreciated. This is my first Android experience, and I've been trying to solve this stupid text-fade-in issue for a full week with no luck. At this point I'm almost ready to abandon mobile as a platform because of how painful every minor change has been so far.
ViewPager keeps the next page in memory & this is it's default behaviour. You could adjust it by calling like:
viewPager.setOffscreenPageLimit(2);
However this might not be useful as if you pass 0 in above method, viewPager will ignore it.
You are going in right direction. I believe now problem is in your ScreenSlidePagerAdapter. In getItem(int position) you might have something like
if(position == 1)
return new PageFragment();
instead change the adapter to something like following,
public class ScreenSlidePagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
public ScreenSlidePagerAdapter(FragmentManager fm, List<Item> items) {
super(fm);
for (Item item : items) {
mFragments.add(new PageFragment());
}
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position); // Return from list instead of new PagerFragment()
}
}
I have the similar problem as yours, onPageSelected() is called before the fragments are initialized, but your description is not detailed enough, such as how you select the second page.
When adapter is fed with Fragments, or we say getCount() > 0, getItem() will whatever returns a Fragment, which is not null. But this doesn't mean it is initialized, at least it doesn't if you extend from FragmentStatePagerAdapter.
when adapter is fed with data and called notifyDataSetChange(), adapter will initialize the first two pages by default. If you call setCurrentItem() to move to other pages immediately after notifyDataSetChange() the issue might happen. During the runtime, setCurrentItem() -> onPageSelected() might be called before the fragments are initialized.
my solution is using view.post() when setCurrentItem(). e.g.
viewPager.post(() -> viewPager.setCurrentItem(index));

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()).

FragmentPagerAdapter getItem is not called

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.

Replace a Fragment in a ViewPager using FragmentPagerAdapter

I am using a ViewPager with 4 pages, and I'm looking for an efficient way to replace/switch between fragments in each page.
This is the interaction pattern that I'm trying to create:
User presses a button on a page that currently holds fragment A
Fragment A is swapped out for some new fragment B
The user does some work in fragment B, and then presses a button when he/she is done
Fragment B is removed, and is replaced by fragment A (the original fragment)
I've found a way to do this, but it seems to have significant flaws. The solution involves removing the original fragment, and then overriding getItemPosition (essentially the method described in this related question):
//An array to keep track of the currently visible fragment in each page
private final Fragment[] activeFragments= new Fragment[4];
public void openFragmentB(ViewPager pager, int position) {
startUpdate(pager);
//Remove the original fragment
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.remove(activeFragments[position]);
transaction.commit();
//Create a new tile search fragment to replace the original fragment
activeFragments[position] = FragmentB.newInstance();
pageStates[position] = PageState.STATE_B;
finishUpdate(pager);
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object) {
//If the main fragment is not active, return POSITION_NONE
if(object instanceof FragmentA) {
FragmentA a = (FragmentA) object;
if(pageStates[a.getPosition()] != PageState.STATE_A) {
return POSITION_NONE;
}
}
//If the secondary fragment is not active, return POSITION_NONE
if(object instanceof FragmentB) {
FragmentB b = (FragmentB) object;
if(pageStates[b.getPosition()] != PageState.STATE_B) {
return POSITION_NONE;
}
}
return POSITION_UNCHANGED;
}
This method works, but has undesirable side effects. Removing the fragment and setting it's position to POSITION_NONE causes the fragment to be destroyed. So when the user finishes using FragmentB, I would need to create a new instance of FragmentA instead of reusing the original fragment. The main fragments in the pager (FragmentA in this example) will contain relatively large database backed lists, so I want to avoid recreating them if possible.
Essentially I just want to keep references to my 4 main fragments and swap them in and out of pages without having to recreate them every time. Any ideas?
A simple way to avoid recreating your Fragments is to keep them as member variables in your Activity. I do this anyway in conjunction with onRetainCustomNonConfigurationInstance() order to retain my fragments during configuration changes (mostly screen rotation). I keep my Fragments in a 'retainer' object since onRetainCustomNonConfigurationInstance only returns a single object.
In your case, instead of calling Fragment.newInstance() all the time, just check to see if the fragments contained in the retainer object is null before creating a new one. If it isn't null, just re-use the previous instance. This checking should happen in your ViewPager adapter's getItem(int) method.
In effect, doing this basically means you are handling whether or not Fragments are recycled when getItem is called, and overriding the getItemPosition(Object) method to always return POSITION_NONE when for relevant Segments.
FragmentPagerAdapter provides an overrideable method called getItemId that will help you here.
If you assign a unique long value to each Fragment in your collection, and return that in this method, it will force the ViewPager to reload a page when it notices the id has changed.
Better late than never, I hope this helps somebody out there!

Categories

Resources