Unable to instantiate fragment androidx.navigation.fragment.NavHostFragment

Viewed 3627

Error

Unable to instantiate fragment androidx.navigation.fragment.NavHostFragment: make sure class name exists, is public, and has an empty constructor that is public.

ActivityLayout

 <fragment
        android:id="@+id/my_nav_host_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/app_nav" />

Activity

class HomeActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
    }
}

Fragment

class MovieListFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_movie_list, container, false)
    }
}

Dependency Used:

implementation('android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha07') {
    exclude group: "com.android.support"
}
implementation('android.arch.navigation:navigation-ui-ktx:1.0.0-alpha07') {
    exclude group: "com.android.support"
}
3 Answers

If its happening only on the proguarded version, you might have forgotten to add the proguard rule. Add the below rule in your proguard file

-keepnames class androidx.navigation.fragment.NavHostFragment

try with this

dependencies {
    def nav_version = "2.1.0-alpha01"
    implementation "androidx.navigation:navigation-fragment:$nav_version" // For Kotlin use navigation-fragment-ktx
    implementation "androidx.navigation:navigation-ui:$nav_version" // For Kotlin use navigation-ui-ktx
}

This happen when you are not set navigationGraph correctly. May be it is a bug or not. There are below reason this error occurred. Accidentally you add HomeActivity in your navigationGraph and also added MovieListFragment and connected MovieListFragment to HomeActivity. And then delete HomeActivity from graph. So the MovieListFragment id not changed may be its krrp the map. I found this issue in my project. Event i reopen the project but nothing luck. So i delete MovieListFragment from graph (only from graph). Then again add the MovieListFragment then it working again.

In my project HomeActivity was MainActivity and MovieListFragment was DashboardFragment.

Related