Skip to content

Android Navigation Component — Complete Guide

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Android Navigation Component. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Your NavController crashes with navigation destination unknown, or the back button doesn't work as expected after navigating.

Wrong Approach ❌

// Setting NavController manually — simple but fragile
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val navController = findNavController(R.id.nav_host_fragment)
        navController.navigate(R.id.action_to_home) // May crash if nav graph not set
    }
}
// Using AppBarConfiguration without proper setup
val navController = findNavController(R.id.nav_host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController) // Works but...
// Missing onSupportNavigateUp override

Output: IllegalArgumentException: navigation destination unknown. Back button doesn't work.

Right Approach ✅

class MainActivity : AppCompatActivity() {
    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val navHostFragment = supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController = navHostFragment.navController

        // Set up action bar with navigation
        val appBarConfiguration = AppBarConfiguration(
            setOf(R.id.homeFragment, R.id.dashboardFragment) // Top-level destinations
        )
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp() || super.onSupportNavigateUp()
    }
}

// Safe navigation using NavDirections
fun safeNavigate() {
    try {
        findNavController().navigate(
            HomeFragmentDirections.actionHomeToDetails(itemId = 42)
        )
    } catch (e: IllegalArgumentException) {
        // Handle navigation error gracefully
    }
}

Output: Proper navigation with working back button and action bar integration.

Prevention

  • Always use NavDirections (generated by Safe Args) for navigation.
  • Override onSupportNavigateUp() and delegate to navController.navigateUp().
  • Define AppBarConfiguration with top-level destinations.
  • Handle navigation errors with try/catch.

Common Mistakes with navigation component

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between findNavController() and NavHostFragment?

findNavController() finds the NavController from the fragment/view hierarchy. NavHostFragment is the container that hosts the NavController. Use NavHostFragment to access the controller directly.

### How do I handle navigation in a Fragment?

Use findNavController() in Fragment's onCreateView or later. Don't navigate in Fragment's constructor or onAttach.

### Why does my navigation action crash on the first launch?

The navigation graph may not be inflated yet. Use NavController.navigate() after onCreate() is complete or use lifecycleScope.launchWhenCreated.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro