I have a project with 2 fragments. I am looking to pass an iterable from the first fragment to the second. Using navArgs is not an option, since it makes the program crash. Bundle seems to only work with primary data types. Is there a way to go about it, without using some super hacky solution, like passing a string of all the data separated by commas as a string?
Question posted in Android Studio
The official documentation can be found here.
The official documentation can be found here.
2
Answers
The modern way to do this is with a
ViewModel
(here and here or with theFragmentResult
API (last link). Otherwise you’re looking at doing it manually through the parentActivity
– call a function on theActivity
that passes your data to the otherFragment
, that kind of thing.If these
Fragments
are in separateActivities
then you’re looking at making your dataParcelable
so it can go in aBundle
, or serialisation (e.g. the Kotlin Serialization library) so you can put it in aBundle
as aString
, or persist it on disk so you can load it from the nextActivity
. Serialisation libraries are a robust way of turning objects and data into a stream of text (and other formats if you like) but there’s nothing wrong with aString
and some separator character if it’s all you need, e.g. storing a list of indices or IDsYou can use a shared view model.
In your first fragment: