Search code examples
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:

    • Data can be stored on Application class level. Application class runs for all application lifecycle. Every fragment can get Application instance from its activity like activity?.getApplication().
    • Data can be stored on Activity level if all fragments run in a single activity. Activity can be obtained from Fragment using activity or requireActivity().
    • Data can be stored on a parent fragment level if all fragments run in this parent fragment. It can be obtained from child fragments using parentFragment.

    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:

    • The Shared ViewModel is just a special case of activity-level approach as ViewModel instance is stored in Activity scope.
    • The SharedPrefrences like any "database" approach is a special case of application-level approach as SharedPreferences is stored on application-level (in the file storage) no matter where you create its instance. (And SharedPreferences persists data across application starts, so it's not your option)