title: In Android Navigation Architecture, how can I check if current Fragment is the last one?
body: <p>I need to display custom <code>AlertDialog</code>, but only when there are no more fragments after calling <code>NavController.navigateUp()</code>. My current code does something similar, but there is a bug to it:</p>
  
  <pre><code>override fun onBackPressed() {
  
      if (navController.navigateUp()) {
          return
      }
  
      showQuitDialog()
  }
  </code></pre>
  
  <p>This somewhat works, but if I cancel the <code>AlertDialog</code> and don't quit the app, <code>navController</code> already navigated up to <code>NavGraph</code> root, which is not the fragment in which I was when <code>AlertDialog</code> appeared. So, if I try to use any navigation action from that fragment, I get error:</p>
  
  <blockquote>
    <p>java.lang.IllegalArgumentException: navigation destination
    com.example.test/actionNavigateToNextFragment is unknown to this NavController</p>
  </blockquote>
  
  <p>This could be resolved, if I had access to <code>mBackStack</code> field in <code>NavController</code>, but it's <code>package private</code>, and I can't use reflection in my current project. But if it was <code>public</code>, I would use it the following way:</p>
  
  <pre><code>override fun onBackPressed() {
  
      // 2 because first one is NavGraph, second one is last fragment on the stack
      if(navController.mBackStack.size &gt; 2) { 
          navController.navigateUp()
          return
      }
  
      showQuitDialog()
  }
  </code></pre>
  
  <p>Is there a way to do this without reflection?</p>