mraviator
mraviator

Reputation: 4074

getFragmentManager() returns null

My app targets API 8 and higher and uses ActionbarSherlock. The Activity extends SherlockFragmentActivity. My fragment adapter for the viewpager is as follows:

public class MyFragmentAdapter extends FragmentPagerAdapter {

  public Fragment getItem(int position) {
        ...
    }

  @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);

        FragmentManager manager = ((ListFragment) object).getSherlockActivity().getSupportFragmentManager();
        FragmentTransaction trans = manager.beginTransaction();
        trans.remove((Fragment) object);
        trans.commit();
    }
}

The destroyItem is used to remove a page of a FragmentPagerAdapter. This works fine the first time, maybe the first two times a page is deleted. But at some point of continued page deletion, the manager returns null and the app crashes on the manager.beginTransaction() line.

I can't seem to figure out why this is...

Upvotes: 1

Views: 2468

Answers (2)

Finally, some days ago I could find my error.

The solution is simple:

Just create a new Bundle variable as a global variable

Bundle datosGuardados;

to store the data of savedInstanceState

datosGuardados = savedInstanceState;

and finally just check if it is null before than using any getFragmentManager

if (datosGuardados != null) infoF = (InformacionFragment) getFragmentManager().findFragmentById(R.id.posicionamiento_layout);

Upvotes: 0

mraviator
mraviator

Reputation: 4074

I figured out the problem. It turns out the ListFragment passed into the destroyItem has its FragmentManager == null because I'm not properly deleting nulled WeakReference items in the List.

Upvotes: 1

Related Questions