I need to set a Fragment to nav graph programmatically. I have tried the below approach to set it in my activity but getting the below error "Fatal Exception: java.lang.IllegalStateException: Cannot remove Fragment attached to a different FragmentManager. " Can anyone please help pointing to what I am doing wrong.
<androidx.fragment.app.FragmentContainerView
android:id="@+id/main_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/homeFragment">
<fragment android:id="@+id/profileFragment" />
<fragment android:id="@+id/homeFragment"
android:name="HomeFragment"
android:label="fragment_home"
tools:layout="@layout/fragment_home"/>
</navigation>
Fragment profileFragment = ProfileFragment()
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.main_nav_host_fragment);
NavDestination profileNode = navHostFragment.getNavController().getGraph().findNode(R.id.profileFragment);
((FragmentNavigator.Destination) startDestNode).setClassName(profileFragment.getClass().getName());
Error Fatal Exception: java.lang.IllegalStateException: Cannot remove Fragment attached to a different FragmentManager.
Fragment ProfileFragment{32a2ed0 (d41fc341-baf2-4266-948a-866fba7e57b5) id=0x7f09028b profile_fragment} is already attached to a FragmentManager. at androidx.fragment.app.BackStackRecord.remove(BackStackRecord.java:316)