Empty Constructor For Extended Fragment
Solution 1:
It is recommended to have an empty constructor in fragment class, since in some cases like screen rotation, the Android system will invoke your fragment's empty constructor for recreating your fragment.
To answer your question, your app will work even if you don't provide an empty constructor as long as you don't have any parameterized constructor in your fragment. This is because the java compiler will add an empty constructor automatically when you don't provide any constructor in the class.
Compiler will not add an empty constructor automatically if you have defined any parameterized constructor in your class. In this case you must define an empty constructor explicitly if you know that someone will create an object of your class with no arguments. This is generic java compiler behavior, not specific to android only.
Since it is a common mistake that people forget to add default constructor when there are parameterized constructors defined in the class. So the android developer web site insists to create the empty constructor in fragment to be in safer side. It doesn't matter whether the empty constructor is generated or provided by you, as long as it is present in the fragment.
Solution 2:
The empty constructor is needed for anything that happens to call either of these static Fragment methods:
public static Fragment instantiate (Context context, String fname)
public static Fragment instantiate (Context context, String fname, Bundle args)
The Android framework uses these methods to create Fragments defined in your XML layouts. It also will use them when restoring a Fragment's Activity state (for example, on an orientation change.)
If you don't define an empty constructor, and one of the aforementioned methods above is called, you'll get a java.lang.InstantiationException.
If you look at the Fragment source code, you'll see that these methods call the fragment class' newInstance() method. This requires a public empty constructor.
Post a Comment for "Empty Constructor For Extended Fragment"