I'm new to android actually. I'm now confused about how to implementing a newInstance() inside a fragment. I have 2 fragments and 1 Activity here :
- Fragment A as an Abstract Class
- Fragment B as a Main Fragment Class that contain parameters
- MainActivity.kt as the Activity
So I got an error log like this :
Caused by androidx.fragment.app.Fragment$e: Unable to instantiate fragment : could not find Fragment constructor
............
Caused by java.lang.NoSuchMethodException: <init> []
at java.lang.Class.getConstructor0
Based on the log, I think the problem is on the fragment that I haven't initialized any 0-arg constructor. So because of this, I want to add a companion object for newInstance() inside my fragment but I can't, here's my FragmentA.kt and FragmentB.kt :
FragmentA.kt
abstract class FragmentA: BottomSheetDialogFragment() {
companion object {
fun newInstance(): FragmentA{
return FragmentA() //Got a red mark here, because I cannot create newInstance() in an abstract class
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(DialogFragment...,getStyle)
}
}
FragmentB.kt
class FragmentB(val Parameterss: AnyParametersHere) : FragmentA() {
companion object {
fun newInstance(): FragmentB{
return FragmentB() //Got a red mark here, because it requires parameter inside the FragmentB()
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
..................................................................
return dialog
}
}
MainActivity.kt In the MainActivity.kt, can I add newInstance() to its companion object or not? If not, what's the best solution for this case?
class MainActivity : AppCompatActivity() {
companion object {
fun newInstance(): MainActivity {
return newInstance()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
...................................
val fragmentB= FragmentB(this)
fragmentB.show(supportFragmentManager, FragmentB.TAG)
}
}
I'm confused tho, please if you have any better solutions I would like to appreciate it. Thank you