Search code examples
javaandroidkotlinandroid-architecture-components

How to execute NavController correctly?


enter image description here I run the program. The simulator will show stop. It shows Activity com.example.navigationdemo.MainActivity@1755f0c does not have a NavController set on 2131230916 in logcat. I don't understand why it can't be executed. Please help me. Thank you.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        NavController controller=Navigation.findNavController(this,R.id.fragmentContainerView);
        NavigationUI.setupActionBarWithNavController(this,controller);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController controller=Navigation.findNavController(this,R.id.fragmentContainerView);
        return controller.navigateUp();
        //return super.onSupportNavigateUp();
    }

Solution

  • NavController controller=Navigation.findNavController(this, R.id.fragmentContainerView);
    

    In onCreate() lifecycle method, it's a bit early get the navController using the id of the container fragment as still the layout is not fully built yet.

    Instead you should get it from the supportFragmentManager:

    NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentContainerView); 
    if (navHostFragment != null) {
         NavController controller = navHostFragment.getNavController();
         NavigationUI.setupActionBarWithNavController(this, controller);
    }