Dynamic feature: Unable to instantiate fragment : make sure class name exists

1k views Asked by At

I'm trying to load my fragment that lives in a dynamic feature module. However, I keep getting a crash:

val f = FragmentFactory().instantiate(classLoader,
 "com.myapp.customviewdynamicfeature.CustomFragment")

supportFragmentManager.beginTransaction()
.add(R.id.customFragmentContainer, f).commit()
2022-03-25 11:36:54.020 20732-20732/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.myapp.dynamicdeliverysampleapp, PID: 20732
    androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.myapp.customviewdynamicfeature.CustomFragment: make sure class name exists
        at androidx.fragment.app.FragmentFactory.loadFragmentClass(FragmentFactory.java:97)
        at 

I also tried adding this to my dynamic module's proguard

-keep class com.myapp.customviewdynamicfeature.** { *; }

I've also tried reflection:

val f = Class.forName("com.myapp.customviewdynamicfeature.CustomFragment").newInstance() as Fragment

but I get a similar error:

    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:558)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
     Caused by: java.lang.ClassNotFoundException: com.myapp.customviewdynamicfeature.CustomFragment
1

There are 1 answers

0
VIN On BEST ANSWER

I believe I resolved this by upgrading the AndroidX fragment version to 1.5.0. https://developer.android.com/jetpack/androidx/releases/fragment#version_15_2