'Could not find Fragment constructor
I am facing the issue on some devices and getting an error on my crash analytics. A lot of user devices are facing this issue, but on my device it's working fine.
Unable to start activity ComponentInfo{com.ox.outloks.new/com.ox.outloks.new.activities.MainDrawerActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.alchemative.outfitters.outfitters.fragments.ProductsFragment: could not find Fragment constructor
The error is coming at the line which is in activity super.onCreate(savedInstanceState);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Here is ProductsFragment constructor
@SuppressLint("ValidFragment")
public ProductsFragment(String id) {
categoryID = id;
}
Solution 1:[1]
Accepted answer is not entirely correct as of today. With FragmentFactory
you can create fragment such as
MyFragment(arg1:Any, arg2:Any,...) {
}
and instantiate it inside FragmentFactory's instantiate method
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
return when (className) {
MyFragment::class.java.name -> MyFragment(arg1, arg2)
}
}
and set your FragmentFactory as supportFragmentManager's fragment factory before onCreate of Activity, because Android checks out for empty constructor fragment and if you don't provide before onCreate your app will crash as usual behavior.
supporFragmentManager.fragmentFactory = yourFragmentFactoryInstance
Solution 2:[2]
A newer alternative to communicate between an Activity and a Fragment, thus allowing that the Fragment can have an empty constructor would be the use of ViewModels.
Solution 3:[3]
I have just faced this exception. My mistake was calling requireArguments() method before arguments were received by the Fragment
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thracian |
| Solution 2 | Alexander Pacha |
| Solution 3 | Max Siomin |
