androidkotlinfragment

my app crashes when I using navigation component


when I start using navigation component the app crashes . it can`t inflate correctly the fragmentContaner view. the main activity kotlin

package com.example.task2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.NavHost
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.example.task2.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    lateinit var navController: NavController
    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityMainBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.bottomNavMain.menu.findItem(R.id.fragmentHome).isChecked = true

        //nav component
        val navHost = supportFragmentManager.findFragmentById(R.id.main_nav_host) as NavHostFragment
        navController=navHost.navController
        binding.bottomNavMain.setupWithNavController(navController)
    }
}

main activity xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav_main"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_nav"
        style="@style/Widget.MaterialComponents.BottomNavigationView.Colored"
        app:backgroundTint="?attr/colorPrimaryVariant"/>

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/main_nav_host"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_main"
        android:layout_marginBottom="56dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/main_nav"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

navigation graph:

<?xml version="1.0" encoding="utf-8"?>
<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/main_nav"
    app:startDestination="@id/fragmentHome">

    <fragment
        android:id="@+id/fragmentHome"
        android:name="com.example.task2.fragment.FragmentHome"
        android:label="FragmentHome"
        tools:layout="@layout/home_fragment"/>
    <fragment
        android:id="@+id/fragmentRegister"
        android:name="com.example.task2.fragment.FragmentRegister"
        android:label="FragmentRegister"
        tools:layout="@layout/register_fragment">
        <action
            android:id="@+id/action_fragmentRegister_to_fragmentLogin"
            app:destination="@id/fragmentLogin" />
    </fragment>
    <fragment
        android:id="@+id/fragmentProfile"
        android:name="com.example.task2.fragment.FragmentProfile"
        android:label="FragmentProfile"
        tools:layout="@layout/profile_fragment"/>
    <fragment
        android:id="@+id/fragmentLogin"
        android:name="com.example.task2.fragment.FragmentLogin"
        android:label="FragmentLogin"
        tools:layout="@layout/login_fragment">
        <action
            android:id="@+id/action_fragmentLogin_to_fragmentRegister"
            app:destination="@id/fragmentRegister" />
    </fragment>
</navigation>

bottom navigation:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/fragmentRegister"
        android:title="Register"
        android:icon="@drawable/register" />
    <item
        android:title="Home"
        android:id="@+id/fragmentHome"
        android:icon="@drawable/home" />
    <item
        android:title="Profile"
        android:id="@+id/fragmentProfile"
        android:icon="@drawable/profile" />
</menu>

and the error is shown:

  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.task2/com.example.task2.MainActivity}: android.view.InflateException: Binary XML file line #32 in com.example.task2:layout/activity_main: Binary XML file line #32 in com.example.task2:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView

this is the exact message of error:

FATAL EXCEPTION: main
                                                                                                    Process: com.example.task2, PID: 14548
                                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.task2/com.example.task2.MainActivity}: android.view.InflateException: Binary XML file line #32 in com.example.task2:layout/activity_main: Binary XML file line #32 in com.example.task2:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4169)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4325)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2574)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8757)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)
Caused by: android.view.InflateException: Binary XML file line #32 in com.example.task2:layout/activity_main: Binary XML file line #32 in com.example.task2:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: android.view.InflateException: Binary XML file line #32 in com.example.task2:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context androidx.fragment.app.FragmentHostCallback.getContext()' on a null object reference
at androidx.fragment.app.FragmentManager$3.instantiate(FragmentManager.java:525)
at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.kt:153)
at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:53)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:136)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:247)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:226)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1091)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1019)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:983)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1145)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1106)
at android.view.LayoutInflater.inflate(LayoutInflater.java:692)
at android.view.LayoutInflater.inflate(LayoutInflater.java:544)
at com.example.task2.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:50)
at com.example.task2.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:44)
at com.example.task2.MainActivity.onCreate(MainActivity.kt:15)
at android.app.Activity.performCreate(Activity.java:8591)
at android.app.Activity.performCreate(Activity.java:8570)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1384)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4150)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4325)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2574)
at android.os.Handler.dispatchMessage(Handler.java:106)
--------- beginning of system
2023-11-05 11:03:21.125  1440-1971  WindowManager           system_server                        E  win=Window{18fadc7 u0 com.example.task2/com.example.task2.SplashScreen} destroySurfaces: appStopped=true cleanupOnResume=false win.mWindowRemovalAllowed=false win.mRemoveOnExit=false win.mViewVisibility=4 caller=com.android.server.wm.ActivityRecord.destroySurfaces:6529 com.android.server.wm.ActivityRecord.destroySurfaces:6510 com.android.server.wm.ActivityRecord.notifyAppStopped:6574 com.android.server.wm.ActivityRecord.activityStopped:7162 com.android.server.wm.ActivityClientController.activityStopped:258 android.app.IActivityClientController$Stub.onTransact:613 com.android.server.wm.ActivityClientController.onTransact:136 
2023-11-05 11:03:21.147  1440-1971  WindowManager           system_server                        E  win=Window{40ab30d u0 Splash Screen com.example.task2} destroySurfaces: appStopped=true cleanupOnResume=false win.mWindowRemovalAllowed=false win.mRemoveOnExit=false win.mViewVisibility=8 caller=com.android.server.wm.WindowManagerService.tryStartExitingAnimation:3009 com.android.server.wm.WindowManagerService.relayoutWindow:2720 com.android.server.wm.Session.relayout:274 android.view.IWindowSession$Stub.onTransact:779 com.android.server.wm.Session.onTransact:188 android.os.Binder.execTransactInternal:1321 android.os.Binder.execTransact:1280 

I tried using <fragment .../> instead of but it didn`t work


Solution

  • I copied your project and after 30 minutes of pulling my hair I finally saw it.

    You need to call super.onCreate(savedInstanceState) before anything else.

            super.onCreate(savedInstanceState)
            binding = ActivityMainBinding.inflate(layoutInflater)
            setContentView(binding.root)
            binding.bottomNavMain.menu.findItem(R.id.fragmentHome).isChecked = true