Passing data from one fragment to another (Kotlin)


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?


The modern way to do this is with a ViewModel (here and here or with the FragmentResult API (last link). Otherwise you’re looking at doing it manually through the parent Activity – call a function on the Activity that passes your data to the other Fragment, that kind of thing.

If these Fragments are in separate Activities then you’re looking at making your data Parcelable so it can go in a Bundle, or serialisation (e.g. the Kotlin Serialization library) so you can put it in a Bundle as a String, or persist it on disk so you can load it from the next Activity. 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 a String and some separator character if it’s all you need, e.g. storing a list of indices or IDs

Answered By – cactustictacs

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published