androidandroid-architecture-navigationfragmentmanager

supportFragmentManager.findFragmentById returning null


The code I have posted below works when the activity is part of main app. However, when I import the project (of which the activity is a part of) as a library into another project and call the activity via startActivitiy() I have the null issue.

My activity has the following code -

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navHostFragment =
      supportFragmentManager.findFragmentById(R.id.wlimpl_main_activity_nav_fragment)  as NavHostFragment
    navController = navHostFragment.navController
    }

Here, supportFragmentManager.findFragmentById(R.id.wlimpl_main_activity_nav_fragment) is returning null.

XML -

<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView
    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/wlimpl_main_activity_nav_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white_space_white"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/wlimpl_auth_nav_graph"
    tools:context=".MainActivity" />

What am I doing wrong?

Edit:

Checking via supportFragmentManager.fragments shows 0 fragments.


Solution

  • Turns out activity_main in library module was conflicting with activity_main in the main app. I had to rename one of the xml files.