Android activity/fragment responsibilities for data loading

android

Solution

Ideally neither `Activity` nor `Fragment` with UI should contain any "model" logic - these classes should be lightweight and responsible only for UI logic. But when you decide to make a separate model object you have a dilemma to choose where to initialise and store this object and how to deal with configuration changes. And here comes some handy trick:

You can create a model `Fragment` without UI, make it retain instance to deal with configuration changes (it's AFAIK the simplest way to save data across config. changes without troubles) and retrieve it anywhere you need via `findFragmentById()`. You make all expensive operations inside it once (using background thread, of course), store your data and you're done. For more info, see Adding a fragment without a UI section.

UPD: There's now a better way to deal with configuration changes: ViewModel from Google's Architecture Components. Here's a good example.

Problem

When starting a new application for a client, I am asking myself again the same question about who should be responsible for loading data: activities or fragments. I have taken both options for various apps and I was wondering which pattern is best according to you in terms of: - limiting the code complexity. - handling edge cases (like screen rotation, screen going power save, loss of connectivity, etc.) Option 1 - Activity loads data & fragment only displays it This allows to have fragments that are just fed a bunch of objects to display. They know nothing about loading data and how we load that. On the other side, the activity loads data using whichever method is required (for instance initially the latest 50 entries and on a search, loads the search result). It then passes it to the fragment which displays it. Method to load the data could be anything (from service, from DB, ... fragments only know about POJOs) It's kind of a MVC architecture where the activity is the controller and fragments are the view. Option 2 - Activity arranges fragments & fragments are responsible to fetch the data In this pattern, fragments are autonomous pieces of application. They know how to load the data they are displaying and how to show it to the user. Activities are simply a way to arrange fragments on screen and to coordinate transitions between application activities.

Original source