Search code examples
androidfirebaseandroid-fragmentsandroidx

Why does AndroidFragment results in Unable to instantiate fragment error?


I have a settings activity that has a fragment whose class is implemented as a static inner class.

Settings activity class looks like this

public class SettingsActivity extends AppCompatActivity implements
            PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {...

    public static class HeadingsFragment extends PreferenceFragmentCompat {
         @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {...}
    ...
    }
} 

And the class is referred in the xml like this

<Preference app:fragment="myapp.SettingsActivity$HeadingsFragment" ... />

Then I tried to test this out in emulator and it just worked fine. But got the error below when tested in real devices.

androidx.fragment.app.Fragment$e: Unable to instantiate fragment myapp.SettingsActivity$HeadingsFragment: make sure class name exists

Tried to capture a Robot Script and tested with multiple different devices in Firebase, still got the error.

Please note that I was able to successfully capture Robot script only because it worked on an emulator.

What might be causing this problem?

Update:

  1. Tried by making the class as a standalone public class (instead of static inner class) and still got the error.
  2. Analysed the generated APK and the class was present in the classes2.dex in both the cases

Solution

  • I tried the solution as provided here

    Basically it was messed up by proguard-rules. Adding these lines to proguard-rules.pro file solved the problem

    -keep public class * extends androidx.preference.Preference
    -keep public class * extends androidx.preference.PreferenceFragmentCompat