Unable to instantiate fragment make sure class name exists

For me this error occurs after moving the XxxFragment.kt file using the refactoring feature of AndroidStudio.

It is important to check every place where the Fragment is referenced to find the cause. Some locations are not covered by refactoring. You can find all places while using the global search (Press Shift twice) for XxxFragment.

In my case two places where not refactored automatically:

  • android:name of the fragment in the nav_graph.xml
  • tools:context import in the fragment_xxx.xml file itself.

TL;DR:

If you recently migrated files or did any form of copy and paste, check that all your files have an updated package name.

Full story:

I created a new module and then copied and pasted the entire java and res directories from another module after which I deleted the old module. To avoid any possible conflicts, I checked all the Kotlin/Java files and renamed the package name to reflect the name of the new package that the files now belonged to. Here's what I mean:

From:

com.myapp.oldmodule.presentation.thisfile

To:

com.myapp.newmodule.presentation.thisfile

Normally, this should have resolved any potential issue. My mistake however was that I forgot to update the navigation-graph file as well; It still had references that contained the old/deleted module.


Found that, you logcat says everything

 Caused by: java.lang.ClassNotFoundException: com.paad.todoList.ToDoListFragment

Your package name is not correct. use com.paad.todolist instead of com.paad.todoList

This post reminds me the TV Show dialog, Sherlock : You see but you do not observe :) :)