1

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.

AndroidDev123
  • 280
  • 3
  • 24

1 Answers1

1

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)

92AlanC
  • 1,327
  • 2
  • 14
  • 33
  • Im attempting to do this. so far I did: val gson = Gson() val json: String = gson.toJson(newCheckIn) viewModel.saveGsonCheckIn(json) – AndroidDev123 Sep 25 '20 at 15:05
  • Then in the viewmodel I did this: fun saveGsonCheckIn(json: String) { editor.putString(CHECKIN, json) editor.apply() } fun setGsonCheckIn(json: String): CheckIn? { val checkInSaved = sharedPreferences.getString(CHECKIN, json) return gson.fromJson(checkInSaved, CheckIn::class.java) } – AndroidDev123 Sep 25 '20 at 15:05
  • But Im struggling to get the data from the vm back into the fragment – AndroidDev123 Sep 25 '20 at 15:06
  • I'm afraid that's not really the topic of your question. You wanted to pass data backwards after pressing the back button and you managed to do it from what it seems. Now with regards to retrieving data from SharedPreferences that's another issue – 92AlanC Sep 25 '20 at 15:17