Reputation: 3537
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.
Upvotes: 1
Views: 112
Reputation: 16849
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.
Upvotes: 1