Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android fragments: is empty constructor really required?

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,

  1. Why does it work when orientation does not change?
  2. Why does it fail when orientation is changed?
  3. What are the differences in activity an fragment life cycles when orientation changes vs activity just created?

Thanks a lot

like image 475
Jason Oviedo Avatar asked Sep 22 '14 22:09

Jason Oviedo


1 Answers

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.

like image 63
CommonsWare Avatar answered Oct 13 '22 00:10

CommonsWare