Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager android android

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager


This seems to be a bug in the newly added support for nested fragments. Basically, the child FragmentManager ends up with a broken internal state when it is detached from the activity. A short-term workaround that fixed it for me is to add the following to onDetach() of every Fragment which you call getChildFragmentManager() on:

@Overridepublic void onDetach() {    super.onDetach();    try {        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");        childFragmentManager.setAccessible(true);        childFragmentManager.set(this, null);    } catch (NoSuchFieldException e) {        throw new RuntimeException(e);    } catch (IllegalAccessException e) {        throw new RuntimeException(e);    }}


I'm having exactly the same problem.The only workaround I've found, is to replace the fragments by a new instance, each time the tabs are changed.

ft.replace(R.id.fragment_container, Fragment.instantiate(PlayerMainActivity.this, fragment.getClass().getName()));

Not a real solution, but i haven't found a way to reuse the previous fragment instance...


I encountered the same issue when calling super.onCreate() at the end of my method. The reason: attachActivity() is called in onCreate() of FragmentActivity. When overriding onCreate() and, for example, creating tabs, the Tab manager will try to switch to a fragment while not having the activity attached to the FragmentManager.

Simple solution: Move the call to super.onCreate() to the head of the function body.

In general, it seems there are loads of reasons this issue may occur. This is just another one ...

Matthias