Search code examples
androidandroid-fragmentsandroid-jetpackandroid-jetpack-navigation

Jetpack Navigation initializes the fragment before the activity: so ui actions crash


I updated my project to kotlin 1.5.20 and jetpack navigation like this

    implementation "androidx.navigation:navigation-fragment-ktx:2.3.5"
    implementation "androidx.navigation:navigation-ui-ktx:2.3.5"

Now my app crashes. The reason is a little bit strange. In my startDestination-Fragment I have UI actions for the activity. For example, depending on the last score, the fragment must adjust the title. So not a special thing.

The app crashes because the xml could not inflated:

     Caused by: android.view.InflateException: Binary XML file line #83: Error inflating class fragment
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

Including the fragment into the activity is standard code:

 <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        <!-- ... some- constraint stuff -->
        app:navGraph="@navigation/nav_graph" />

I put a log message in my onCreate in my activity and on onViewCreated in the fragment. My log shows a strange lifecycle:

2021-07-10 17:42:08.097 28021-28021/com.x E/Lifecycle: Create Game Fragment
2021-07-10 17:42:08.141 28021-28021/com.x E/Lifecycle: Create Game Holder Activity

My assumption so far was that the activity initializes first and then the fragment. I would have expected the log in exactly the other order. The "fix" is very hacky.

   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        Log.e("Lifecycle", "Create Game Fragment")
        lifecycleScope.launch {
           // delay(1)
            doActivityUIChanges()
        }

    }

When I use a delay(1) everything worked. When I don't use a delay the app is crashing.

It's really weird. Am I misunderstanding the lifecycle? I really would appreciate another solution. My fix is not very clean haha


Solution

  • Replace your tag for <androidx.fragment.app.FragmentContainerView> Is not clear why, but is the recommend of doing according to the official documentation: https://developer.android.com/guide/navigation/navigation-getting-started