2

I have an ActivityA and which host a fragmentA

onAttach() method of fragmentA, I need to check some conditions and if it fails, I need to finish the activity. I'm finishing the activity by calling getActivity().finish().

Even after I call the finish method, it is still calling the onCreate(), onCreateView() and onViewCreated() methods in fragmentA .

Is there any way I can stop these calls?

Athena
  • 3,200
  • 3
  • 27
  • 35

1 Answers1

1

As @DeeV commented, I would check conditions before attaching a Fragment. In this case you don't have to deal with fragment lifecycle at all which is a cleaner way.

If this is not possible, there is a hacky way. You can call finish() in onAttach() and then use activity's method isFinishing() which returns a boolean flag. I think this should solve the problem.

E.g. in your fragment's onCreate method:

if (getActivity().isFinishing()) {
   // finish was called in onAttach
}
Gennadii Saprykin
  • 4,505
  • 8
  • 31
  • 41
  • Thank you Gennadii yes that is an option, , but then I need to do isFinishing() check in all the methods like onCreate(), onViewCreated(), onViewRestored() methods. So wondering if there any other options than adding this check in these methods – Punnya Cipson Jul 15 '16 at 22:38
  • No, I don't think it's possible to avoid this. The way it works in android is that it adds messages like `onCreate()`, `onStart()` etc. to the UI message queue which means they will be processed unless you remove them from the queue explicitly. And of course you can't remove them from the queue because you don't have a `Runnable` or token to do this. So you either do this hacky way with `isFinishing()` method call, or try to avoid attaching the fragment itself. Are you sure you can't avoid this? I think this should be your main focus, trying to avoid fragment attach event. – Gennadii Saprykin Jul 15 '16 at 22:54
  • The whole situation looks wrong to me: fragment decides if it should close the activity when it attaches to it. `onAttach` is supposed to be used for attaching purposes only, such as storing an activity reference, casting it to some interface that fragment will be using for interaction with the activity. So I'm pretty sure the problem is in your use case itself, not in fragment callbacks. That's why you basically have to do those hacks.. Fragment is not meant to be used like that. – Gennadii Saprykin Jul 15 '16 at 22:56