Making loading data lifecycle aware

Ian Lake
Android Developers
Published in
10 min readFeb 3, 2016

Note: if you’re looking for a modern, flexible solution to this problem that doesn’t rely on Loaders (the chosen solution here), check out the Lifecycle Aware Data Loading with Architecture Components blog post.

Building a dynamic Android app requires dynamic data. But I hope we’ve all moved beyond loading data on the UI thread (#perfmatters or something like that). That discussion can go on for seasons and seasons, but let’s focus in on one case: loading data specifically for display in your Activity or Fragment with Loaders.

Much of the talk on Loaders is around CursorLoader, but Loaders are much more versatile than only working with Cursors.

While Loaders exist as part of the framework on API 11 and higher, they’re also part of the Support v4 Library and bring the latest features (and bugfixes!) to every API 4 and higher devices.

What’s so special about Loaders?

By default, device configuration changes such as rotating your screen involve restarting your whole Activity (one of the many reasons it is so critical not to keep a reference to your Activity or any Views). The best part about Loaders is that Loaders survive configuration changes. That expensive data you just retrieved? Still there for immediate retrieval when the activity comes back up. Data is queued up for delivery so you aren’t going to lose data during device configurations either.

But even better: Loaders don’t stay around forever. They’ll be automatically cleaned up when the requesting Activity or Fragment is permanently destroyed. That means no lingering, unnecessary loads.

These two facts together mean that they perfectly match the lifecycle you actually care about: when you have data to show.

I don’t believe you

Perhaps an example will be enlightening. Let’s say you are converting a regular AsyncTask to the loader equivalent, aptly named AsyncTaskLoader:

public static class JsonAsyncTaskLoader extends
AsyncTaskLoader<List<String>> {
// You probably have something more complicated
// than just a String. Roll with me
private List<String> mData;
public JsonAsyncTaskLoader(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
if (mData != null) {
// Use cached data
deliverResult(mData);
} else {
// We have no data, so kick off loading it
forceLoad();
}

}
@Override
public List<String> loadInBackground() {
// This is on a background thread
// Good to know: the Context returned by getContext()
// is the application context

File jsonFile = new File(
getContext().getFilesDir(), "downloaded.json");
List<String> data = new ArrayList<>();
// Parse the JSON using the library of your choice
// Check isLoadInBackgroundCanceled() to cancel out early
return data;
}
@Override
public void deliverResult(List<String> data) {
// We’ll save the data for later retrieval
mData = data;
// We can do any pre-processing we want here
// Just remember this is on the UI thread so nothing lengthy!
super.deliverResult(data);
}
}

Looks pretty similar to an AsyncTask, but we can now hold onto results in a member variable and immediately return them back after configuration changes by immediately calling deliverResult() in our onStartLoading() method. Note how we don’t call forceLoad() if we have cached data — this is how we save ourselves from constantly reloading the data!

You might have noticed the static keyword when declaring the JsonAsyncTaskLoader. It is incredibly important that your Loader does not contain any reference to any containing Activity or Fragment and that includes the implicit reference created by non-static inner classes. Obviously, if you’re not declaring your Loader as an inner class, you won’t need the static keyword.

Not good enough — what if my data changes?

What the simple example fails to get at is that you aren’t limited to just loading a single time — your Loader is also the perfect place to put in broadcast receivers, a ContentObserver (something CursorLoader does for you), a FileObserver, or a OnSharedPreferenceChangeListener. All of a sudden your Loader can react to changes elsewhere and reload its data. Let’s augment our previous Loader with a FileObserver:

public static class JsonAsyncTaskLoader extends
AsyncTaskLoader<List<String>> {
// You probably have something more complicated
// than just a String. Roll with me
private List<String> mData;
private FileObserver mFileObserver; public JsonAsyncTaskLoader(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
if (mData != null) {
// Use cached data
deliverResult(mData);
}
if (mFileObserver == null) {
String path = new File(
getContext().getFilesDir(), "downloaded.json").getPath();
mFileObserver = new FileObserver(path) {
@Override
public void onEvent(int event, String path) {
// Notify the loader to reload the data
onContentChanged();
// If the loader is started, this will kick off
// loadInBackground() immediately. Otherwise,
// the fact that something changed will be cached
// and can be later retrieved via takeContentChanged()
}
};
mFileObserver.startWatching();
}
if (takeContentChanged() || mData == null) {
// Something has changed or we have no data,
// so kick off loading it
forceLoad();
}
}
@Override
public List<String> loadInBackground() {
// This is on a background thread
File jsonFile = new File(
getContext().getFilesDir(), "downloaded.json");
List<String> data = new ArrayList<>();
// Parse the JSON using the library of your choice
return data;
}
@Override
public void deliverResult(List<String> data) {
// We’ll save the data for later retrieval
mData = data;
// We can do any pre-processing we want here
// Just remember this is on the UI thread so nothing lengthy!
super.deliverResult(data);
}
protected void onReset() {
// Stop watching for file changes
if (mFileObserver != null) {
mFileObserver.stopWatching();
mFileObserver = null;
}
}

}

So by hooking into the onStartLoading() callback to start our processing and the final onReset(), we can stay perfectly in sync with the underlying data. We could have used onStopLoading() as the ending callback, but onReset() ensures that we have continuous coverage (even mid-configuration change).

You’ll note the usage of takeContentChanged() in onStartLoading() — this is how your Loader knows that something has changed (i.e.,someone called onContentChanged()) while the Loader was stopped so even if there were cached results, a data load still needs to be done.

Note: we still deliver the old, cached data before loading the new — make sure that’s the right behavior for your app and change onStartLoading() as necessary. For example, you might check for takeContentChanged() and immediately throw away cached results, rather than redeliver them.

Working with the rest of your app: the LoaderManager

Of course, even the best Loader would be nothing if it wasn’t connected to something. That connection point for activities and fragments comes in the form of LoaderManager. You’ll call FragmentActivity’s getSupportLoaderManager() or a Fragment’s getLoaderManager() to get your instance.

In almost every case, there’s only one method you’ll need to call: initLoader(). This is generally called in onCreate() or onActivityCreated() — basically as soon as you know you’ll need to load some data. You’ll pass in a unique id (only within that Activity/Fragment though — not globally unique), pass an optional Bundle, and an instance of LoaderCallbacks.

Note: make sure to upgrade to version 24.0.0 or higher of the Android Support Library if you want to call initLoader() within a Fragment’s onCreate() — there were issues in previous versions of the Support Library (and all framework fragments <API 24) where Loaders would be shared across fragments as noted in this Lint request and this related Google+ post.

You might notice there’s a restartLoader() method in LoaderManager which gives you the ability to force a reload. In most cases, this shouldn’t be necessary if the Loader is managing its own listeners, but it is useful in cases where you want to pass in a different Bundle — you’ll find your existing Loader is destroyed and a new call to onCreateLoader() is done.

We mentioned using onReset() instead of onStopLoading() for our FileObserver example above — here we can see where this interacts with the normal lifecycle. Just by calling initLoader(), we’ve hooked into the Activity/Fragment lifecycle and onStopLoading() will be called when the corresponding onStop() is called. However, onReset() is only called when you specifically call destroyLoader() or automatically when the Activity/Fragment is completely destroyed.

LoaderCallbacks

LoaderCallbacks is where everything actually happens. And by ‘everything’, we mean three callbacks:

So our previous example might look like:

// A RecyclerView.Adapter which will display the data
private MyAdapter mAdapter;
// Our Callbacks. Could also have the Activity/Fragment implement
// LoaderManager.LoaderCallbacks<List<String>>
private LoaderManager.LoaderCallbacks<List<String>>
mLoaderCallbacks =
new LoaderManager.LoaderCallbacks<List<String>>() {
@Override
public Loader<List<String>> onCreateLoader(
int id, Bundle args) {
return new JsonAsyncTaskLoader(MainActivity.this);
}
@Override
public void onLoadFinished(
Loader<List<String>> loader, List<String> data) {
// Display our data, for instance updating our adapter
mAdapter.setData(data);
}
@Override
public void onLoaderReset(Loader<List<String>> loader) {
// Loader reset, throw away our data,
// unregister any listeners, etc.
mAdapter.setData(null);
// Of course, unless you use destroyLoader(),
// this is called when everything is already dying
// so a completely empty onLoaderReset() is
// totally acceptable
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The usual onCreate() — setContentView(), etc.
getSupportLoaderManager().initLoader(0, null, mLoaderCallbacks);
}

Of course, there’s no hard requirement to use LoaderManager, although you’ll find life much easier if you do. Feel free to look at the FragmentActivity source and the LoaderManager source for a detailed look into everything it is giving you.

Cool, but I don’t need a background thread

AsyncTaskLoader tries to make it easy to get off the background thread, but if you’ve already done your own background threading or rely on event bus / subscription models, AsyncTaskLoader is overkill. Let’s take an example of loading location changes without throwing all that code into your Activity/Fragment:

public static class LocationLoader extends Loader<Location>
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private ConnectionResult mConnectionResult;
public LocationLoader(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
if (mLastLocation != null) {
deliverResult(mLastLocation);
}
if (mGoogleApiClient == null) {
mGoogleApiClient =
new GoogleApiClient.Builder(getContext(), this, this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
else if (mGoogleApiClient.isConnected()) {
// Request updates
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, new LocationRequest(), this);
}
}
@Override
protected void onStopLoading() {
// Reduce battery usage when the activity is stopped
// This helps us handle if the home button is pressed
// And the loader is stopped but not yet destroyed
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
new LocationRequest()
.setPriority(LocationRequest.PRIORITY_NO_POWER),
this);
}
}
@Override
protected void onForceLoad() {
// Resend the last known location if we have one
if (mLastLocation != null) {
deliverResult(mLastLocation);
}
// Try to reconnect if we aren’t connected
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
@Override
public void onConnected(Bundle connectionHint) {
mConnectionResult = null;
// Try to immediately return a result
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
deliverResult(mLastLocation);
}
// Request updates
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, new LocationRequest(), this);
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
// Deliver the location changes
deliverResult(location);
}
@Override
public void onConnectionSuspended(int cause) {
// Cry softly, hope it comes back on its own
}
@Override
public void onConnectionFailed(
@NonNull ConnectionResult connectionResult) {
mConnectionResult = connectionResult;
// Signal that something has gone wrong.
deliverResult(null);
}
/**
* Retrieve the ConnectionResult associated with a null
* Location to aid in recovering from connection failures.
* Call startResolutionForResult() and then restart the
* loader when the result is returned.
* @return The last ConnectionResult
*/
public ConnectionResult getConnectionResult() {
return mConnectionResult;
}
@Override
protected void onReset() {
LocationServices.FusedLocationApi
.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}

So here we can see the three main components:

  • onStartLoading() kicks off the subscription process (in this case, by connecting to Google Play services)
  • onStopLoading() is when we’re put into the background (either temporarily on rotation or when the Home button is pressed and the loader is put into the background) so we reduce battery/processor usage
  • As we get results we call deliverResult()
  • Finally, we disconnect and clean up in onReset()

Here the Loader framework knew nothing about Google Play services, but we can still encapsulate that logic in one place and rely on a single onLoadFinished() with an updated location. This type of encapsulation also helps with switching out location providers — the rest of your code does not care how or where the Location objects come from.

Note: in this case, failures are reported by sending a null Location. This signals the listening Activity/Fragment to call getConnectionResult() and handle the failure. Remember that the onLoadFinished() includes a reference to the Loader so any status you have can be retrieved at that point.

Loaders: for data only

So a Loader has one goal in life: give you up-to-date information. It does that by surviving device configuration changes and containing its own data observers. This means that the rest of your Activity/Fragment doesn’t need to know those details. (Nor should your Loader know anything about how the data is being used!)

If you’ve been using retained Fragments (those that call setRetainInstance(true)) to store data across configuration changes, strongly consider switching from a retained Fragment to a Loader. Retained fragments, while aware of the overall Activity lifecycle, should be viewed as completely independent entities, while Loaders are tied directly into an Activity or Fragment lifecycle (even child fragments!) and therefore much more appropriate for retrieving exactly the data needed for display. Take for example a case where you are dynamically adding or removing a fragment — Loaders allow you to tie the loading process to that lifecycle and still avoid configuration changes destroying the loaded data.

That single focus also means that you can test the loading separately from the UI. The examples here just passed in a Context, but you can certainly pass in any required classes (or mocks thereof!) to ease testing. Being entirely event driven, it is also possible to determine exactly what state the Loader is in at any time as well as expose additional state solely for testing.

Note: while there’s a LoaderTestCase designed for framework classes, you’ll need to make a Support Library equivalent from the LoaderTestCase source code if you want to do something similar with the Support v4 Loader (something Nicholas Pike already has done!). This also gives you a good idea of how to interact with a Loader without a LoaderManager.

Now, it is important to mention that Loaders are reactive, recipients of data. They’re not responsible for changing the underlying data. But for what they do, they do fill a needed gap of lifecycle aware components that survive configuration changes and get your data to your UI.

#BuildBetterApps

Join the discussion on the Google+ post and follow the Android Development Patterns Collection for more!

--

--