skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. You can use a shared view model.
    In your first fragment:

    <code>class FirstFragment : Fragment() {
        private lateinit var viewModel: SharedViewModel
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            viewModel = ViewModelProviders.of(requireActivity()).get(SharedViewModel::class.java)
            viewModel.setData(yourIterable)
        }
    }
    
    </code>
    In your second fragment: 
    <code>class SecondFragment : Fragment() {
        private lateinit var viewModel: SharedViewModel
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            viewModel = ViewModelProviders.of(requireActivity()).get(SharedViewModel::class.java)
            val data = viewModel.getData()
        }
    }
    
    </code>
    And your <code>SharedViewModel</code>: 
    <code>class SharedViewModel : ViewModel() {
        private val _data
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search