Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching Fragments too quickly causes: java.lang.IllegalStateException: No activity

I'm not using a ViewPager, and the only places where I am calling any Fragment transactions is on clicking buttons that live on a navbar in my activity's layout.

When I switch to fragments too quickly (like back and forth), I get this exception:

java.lang.IllegalStateException: No activity

It seems to be when I click to switch another Fragment while the first one hasn't completely finished loading. I'm using a FragmentActivity.

Can anyone shed some insight on this?

My code to switch Fragments:

fragmentManager.beginTransaction()
    .replace(R.id.container, old,
        fragment.getClass().getSimpleName())
    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();

Edit: Taking out the transition solved the problem, but I'm wondering if there is a way to do this with transitions in place. My theory is that the transition delays the fragment lifecycle and causes activity to be null when another fragment transaction is initiated.

like image 646
sihrc Avatar asked Sep 29 '22 03:09

sihrc


1 Answers

I run into the same issue today. Turns to be that I was caching my Fragment (which is perfectly valid) but I've been removing/adding it to soon (when still animating)

Try checking: old.isRemoving() before calling .replace(R.id.container, old)

true means it's still in use and re-adding it triggers the issue. You should create a new fragment instance in that case.

My guess is I was trying to re-add a fragment while it's still animating its removal, so two fragment instances are required.

like image 56
gmazzo Avatar answered Dec 06 '22 06:12

gmazzo