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
Fragment
lifecycles. It's a general rule you can implement as you want. A couple of examples below:Application
class level.Application
class runs for all application lifecycle. Every fragment can getApplication
instance from its activity likeactivity?.getApplication()
.Activity
level if all fragments run in a single activity.Activity
can be obtained fromFragment
usingactivity
orrequireActivity()
.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 someval data: Data
as its property, then you should use it something like this:(requireActivity() as MainActivity).data
Clarification on a couple of popular answers:
Shared ViewModel
is just a special case of activity-level approach asViewModel
instance is stored inActivity
scope.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)