1

Like many others, I'm struggling with this error:

java.lang.IllegalStateException: Fragment xyz not attached to Activity

This question offers some ideas on how to deal with this. There are no explanations to the question however, why does a Fragment detach from their Activity in the first place? Does an understanding of why this happens help me to design my app in a way to avoid this happening?

In may case I do not have some asynchronous task and call getResources() when it completes; I call getResources() in the onCreate() method of the Fragment. And sometimes, when I'm navigating my app rather fast, said error surfaces. Is it to be expected that the Fragment is not even necessarily attached to its Activity during its own onCreate() method?

Secondly, the solutions provided in the linked question (guarding getResources() with isAdded() and getActivity() != null) don't help me. There is no reasonable way to deal with getResources() not being available.

user1785730
  • 3,150
  • 4
  • 27
  • 50

1 Answers1

1

Because Android supposes that Activities may be destroyed and recreated to accommodate configuration changes. Fragments, in contrast, are not.

Is it to be expected that the Fragment is not even necessarily attached to its Activity during its own onCreate() method?

Yes, it is "expected." Bad design IMO, but expected.

nmr
  • 16,625
  • 10
  • 53
  • 67
  • For a practical answer to your problem, just create a global Application reference via an explicit Application subclass and use that to query resources. – nmr Dec 30 '18 at 04:07
  • This sounds like Fragments are fundamentally broken and should be avoided. Is that the case? – user1785730 Dec 30 '18 at 16:09
  • I'm not sure. You have to roll a lot of your own stuff to avoid them. It's a value judgement. – nmr Dec 30 '18 at 20:49