Android InstantiationException With Fragment (It Is Public)
CHECK YOUR PROGUARD RULES
The strange thing in my case was, this error popped only in the release build and not in the debug build.
The issue was, I was using a FragmentContainerView
to hold the Fragment
and mentioned the Fragment
class name in the XML itself, like this
<androidx.fragment.app.FragmentContainerView
android:id="@+id/f_navigation_fragment"
class="com.example.MyFragmentClass"
android:layout_width="match_parent"
android:layout_height="match_parent" />
This worked fine in the Debug build (without Proguard Obfuscation) but in the Release build (with Proguard Obfuscation) the actual Fragment
class was Obfuscated and hence the XML was unable to locate it leading to OP's error.
Please refer this link for additional references.
You MUST
have an empty public constructor. Whoever told you to not have a fragment constructor steered you in the wrong direction.
What they might have told you, is to not have a constructor that accepts arguments, since those may not be called by the system when re-creating the fragments. In that case, use the example in the docs to supply arguments to your fragment.
Quoted from the docs :
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. [1], [2]
[1] : https://developer.android.com/reference/android/app/Fragment.html
[2] : https://developer.android.com/reference/android/app/Fragment.html#Fragment()