android – How do I tell my custom FragmentPagerAdapter to stop destroying my fragments?-ThrowExceptions

Exception or error:

I have a ViewPager with a FragmentPagerAdapter, and my app has previously used just two fragments (different types) without issues.

I just added a third fragment, though, and now my adapter/viewpager seems to be destroying my fragments when I get far away from them. For example, if I’m on page 1, page 3 is destroyed and recreated when I get close to it. If I’m on page 3, the same happens to page 1.

This is causing lots of issues in my app. The fragments aren’t very RAM-heavy at all, so how can I stop this from happening?

How to solve:

I believe you are looking for ViewPager.setOffscreenPageLimit().

In your case, the following should keep your fragments in memory and not destroy them.

ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setOffscreenPageLimit(2);

However, I suspect that you are not correctly storing your view state when being destroyed. Your fragments should correctly handle being destroyed/recreated. Your fragments would for example also be destroyed and recreated if an orientation change happens. It could also happen if the user leaves your application and the system later needs memory and destroys your Activity. It should be able to reopen and be in the same state as before. If this is indeed the problem for you, consider saving state in onSaveInstanceState(). The saved state will be presented to you in onCreate where you can initialize the state of the fragment to be the same as the destroyed one.

###

just override this method in FragmentpagerAdapter

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
       // TODO Auto-generated method stub
       super.destroyItem(ViewGroup container, int position, Object object);
}

remove super.destroyItem(ViewGroup container, int position, Object object);

from your code

Leave a Reply

Your email address will not be published. Required fields are marked *