How to update the argument of a destination when going back to it?

59 Views Asked by At

I'm currently trying to implement some sort of account profile where the current user can do some modification to their profile. I already added the profile syncing on the server side, but I'm currently stuck at how do I update the local copy of the account. The calling Fragment of the account profile Fragment is already receiving an account argument so I thought if I could find a way to pass back the updated account, then I'll be golden. With this in mind, I thought maybe I need to listen to back presses and use navigate() to go back to the calling Fragment and passing the updated account to it. But NavController doesn't seem to support it, at least I can't find any function that looks like it lets you listen/override to the back presses on the documentation. I found that you can use this:

requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner){
    
}

but it doesn't seem to work for me. Now I'm getting an error for some reason when the code below was already working previously.

val action = DashboardFragmentDirections.showAccountDetailsFromDashboard(currentAccount)
findNavController().navigate(action)

The error looks like this:

androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.app.name.fragments.management.AccountProfileFragment: could not find Fragment constructor

I already did a couple of invalidate cache and the error still occurs.

What I currently want to do is fix this weird error and find a way to update the received account of the calling Fragment. The process of doing so doesn't matter

1

There are 1 best solutions below

0
On

Not too sure if it's the right way to do things, but this is how I implemented what I wanted to do.

My solution is heavily based on this answer. So here's my code

This needs to be in the MainActivity

val navController = findNavController(R.id.nav_host_fragment_content_main)
setupActionBarWithNavController(navController, appBarConfiguration)
binding.navView.setupWithNavController(navController)

Then on the Fragment that you want to listen the back presses, you add this inside atleast onViewCreated:

/**
 * this is the listener for the toolbar back press
 */
val callback: OnBackPressedCallback =
    object : OnBackPressedCallback(true /* enabled by default */) {
        override fun handleOnBackPressed() {
            val action = AccountProfileFragmentDirections.goBackToDashboardFromAccountProfile(updatedAccount)
            findNavController().navigate(action)
        }
    }

ctx.onBackPressedDispatcher.addCallback(viewLifecycleOwner, callback)

/**
 * this is the listener for the actual back press
 */
val callback2 = requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
    val action = AccountProfileFragmentDirections.goBackToDashboardFromAccountProfile(updatedAccount)
    findNavController().navigate(action)
}