5

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.

sihrc
  • 2,728
  • 2
  • 22
  • 43
  • Have you looked into https://stackoverflow.com/a/17131382/603270 https://stackoverflow.com/a/15656428/603270 ? – shkschneider Apr 28 '15 at 14:20
  • @shkschneider I've looked into those. Apparently thats a bug with the new support library, but I'm not using child fragment managers here. This is just a basic app with like 4 screens accessible via buttons in the activity. – sihrc Apr 28 '15 at 17:23
  • I think your issue is related to getting the context onAttach, have you tried to get the context later? e.g. onActivityCreated – Rarw Apr 28 '15 at 17:40
  • I'm getting my activity reference from the onAttach callback from the fragment. This happens before the fragment is even added. The exception is thrown by the fragment manager. – sihrc Apr 28 '15 at 17:42
  • @sihrc If that is a support library bug, that is bad. Any link to back your assumption? – shkschneider Apr 29 '15 at 08:15
  • Sorry, it's on a private repository, but to reproduce: activity - 2 buttons, 1 fragment container, switch between 2 fragments with transitions should do it. – sihrc Apr 29 '15 at 12:58
  • When I get some time, I can setup an app to do it real quick. Maybe sometime in 4 hours. – sihrc Apr 29 '15 at 12:59
  • Same issue here, no child-fragments, just adding and removing a fragment with a transition to fast triggers it: `java.lang.IllegalStateException: No host` Did you found a solution? – gmazzo Aug 30 '15 at 21:48

1 Answers1

4

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.

gmazzo
  • 1,135
  • 13
  • 15