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.
I won't use a database, since I don't need to permanently store the data. Thank you!
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
Fragmentlifecycles. It's a general rule you can implement as you want. A couple of examples below:Applicationclass level.Applicationclass runs for all application lifecycle. Every fragment can getApplicationinstance from its activity likeactivity?.getApplication().Activitylevel if all fragments run in a single activity.Activitycan be obtained fromFragmentusingactivityorrequireActivity().parentFragment.All these approaches suppose you to cast some "parent" thing to specific interface or implementation. For example, if your fragments run in the
MainActivitywhich is stores someval data: Dataas its property, then you should use it something like this:(requireActivity() as MainActivity).dataClarification on a couple of popular answers:
Shared ViewModelis just a special case of activity-level approach asViewModelinstance is stored inActivityscope.SharedPrefrenceslike 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)