androidandroid-fragmentsandroid-architecture-navigationandroid-architecture

Best way to pass data needed for a later (not following) fragment?


I have an application that needs to collect some data before doing it's main job. So, the first fragment collects data, the second fragment collects data and then the third fragment uses the data. The problem is: data in the first fragment is uncorrelated to the data I collect in the second fragment. How can I pass the data from the first fragment to the third? Should I incrementally pass all the data I collect in the next fragment arguments, or should I store them elsewhere? I'd really like to know what the best practice is.


explicative image


I won't use a database, since I don't need to permanently store the data. Thank you!


Solution

  • As for any best practices, the best answer is "it depends".

    If your app is really small and simple then it's okay to pass data from one screen to another in the arguments bundle.

    A more complex approach is to store data somewhere outside of these Fragment lifecycles. It's a general rule you can implement as you want. A couple of examples below:

    All these approaches suppose you to cast some "parent" thing to specific interface or implementation. For example, if your fragments run in the MainActivity which is stores some val data: Data as its property, then you should use it something like this: (requireActivity() as MainActivity).data

    Clarification on a couple of popular answers: