androidandroid-fragmentsandroid-navigationandroid-bundle

Passing a parcelable bundle backwards using the OnBackPressedCallback


In my app I am using the OnBackPressedCallback and calling the findNavController.popBackStack to manage backwards navigation. One limitation I have encountered is that I cannot find a way to pass a parcelable bundle back when the user clicks the back button.

The use case is simple: Fragment A user inputs some data. It's passed along to Fragment B the user inputs some more data. User decides they want to go back to Fragment A and edit previous data so I want to pass the bundle back so they dont lose the data previously inputted.

Using the Navigation component I could simply attach the bundle when navigating back but using this OnBackPressCallback we do not use the navigation component, thus there is nothing to attach a bundle to.

Does anyone have any potential simple solutions to this? I have already considered SharedPreferences however I am passing an object and SP only allows primatives.


Solution

  • The simplest solution would be to serialise your parcelable into a JSON string, save it to shared preferences then de-serialise it when you need to retrieve that data.

    There are 2 well-known and reliable JSON libraries, if you're not already using one or are not familiar with it: you can use either Gson (Google) or Moshi (Square)