Search code examples
androidkotlinandroid-jetpackandroid-architecture-navigationandroid-navigation

Navigation not working anymore, Error: Ignoring popBackStack to destination as it was not found on the current back stack


Suddenly, the navigation in my app is not working anymore out of nowhere (it literally worked yesterday).

Here is an example: When I navigate from userLoggedInFragment to userLoggedOutFragment, use the parameters app:popUpTo="@id/userLoggedOutFragment" app:popUpToInclusive="true" and then click the back button it still navigates me back to userLoggedInFragment even tho I used popUpTo. I then get the information:

I/NavController: Ignoring popBackStack to destination com.example.app:id/userLoggedOutFragment as it was not found on the current back stack

Here is my fragment code

UserLoggedInFragment

@AndroidEntryPoint
class UserLoggedInFragment : Fragment() {
    private var _binding: FragmentUserLoggedInBinding? = null
    private val binding: FragmentUserLoggedInBinding get() = _binding!!
    private val viewModel: LogoutViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentUserLoggedInBinding.inflate(inflater, container, false)
        return binding.root
    }

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

        binding.lifecycleOwner = viewLifecycleOwner

        binding.btnLogout.btnNext.setOnClickListener { 
          findNavController().navigate(
                UserLoggedInFragmentDirections.actionUserLoggedInFragmentToUserLoggedOutFragment()
            ) 
        }
    }
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

Nav Graph

<fragment
    android:id="@+id/userLoggedInFragment"
    android:name="com.example.app.framework.ui.view.fragment.user.UserLoggedInFragment"
    tools:layout="@layout/fragment_user_logged_in">

    <action
        android:id="@+id/action_userLoggedInFragment_to_userLoggedOutFragment"
        app:destination="@id/userLoggedOutFragment"
        app:popUpTo="@id/userLoggedOutFragment"
        app:popUpToInclusive="true" />
</fragment>

I also have this in many other fragments where I use popUpTo and popUpToIncluse="true". What am I doing wrong??


Solution

  • I found the solution: The problem was that I shouldn't pop to the same destination I am navigating to because the fragment would never be in the backstack. Instead of, you should popTo the fragment you want to be presented, when clicking the back button. In my case, this would be my startdestination aka. homeFragment:

    <action
        android:id="@+id/action_userLogInRegistrationFragment_to_userLoggedInFragment"
        app:destination="@id/userLoggedInFragment"
        app:popUpTo="@id/homeFragment" />