I have an activity with a pager and a FragmentStatePagerAdapter inside (I need to swipe across many pages). As we all know, this adapter creates 3 fragment instances at a time, the one to be displayed, the previous and next ones.
My activity was working really nice using a fragment with only one constructor: it received 1 parameter. When testing, I started to get the infamous message:
Unable to instantiate fragment: make sure class name exists, is public,
and has an empty constructor that is public
The funny part is that this message only shows up right after orientation change, but the app just works if orientation remains still. So,
Thanks a lot
is empty constructor really required?
Yes.
Why does it work when orientation does not change?
Because Android is not trying to recreate your fragments.
Why does it fail when orientation is changed?
Because Android is recreating your fragments.
When a configuration change occurs (e.g., orientation change), by default Android destroys and recreates your activity, and also destroys and recreates the fragments in that activity. The "recreates the fragments" part is why you need the zero-argument public constructor on your fragments. It is also used in other cases, such as with a FragmentStatePagerAdapter
.
Or, to quote the documentation:
All subclasses of Fragment must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the empty constructor is not available, a runtime exception will occur in some cases during state restore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With