LoaderManager.java revision f73c75ca20fcaaee1b0eeaaf756252c33e3099c6
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import android.content.Loader;
20import android.os.Bundle;
21import android.util.Log;
22import android.util.SparseArray;
23
24import java.io.FileDescriptor;
25import java.io.PrintWriter;
26
27/**
28 * Interface associated with an {@link Activity} or {@link Fragment} for managing
29 * one or more {@link android.content.Loader} instances associated with it.  This
30 * helps an application manage longer-running operations in conjunction with the
31 * Activity or Fragment lifecycle; the most common use of this is with a
32 * {@link android.content.CursorLoader}, however applications are free to write
33 * their own loaders for loading other types of data.
34 *
35 * <p>As an example, here is the full implementation of a {@link Fragment}
36 * that displays a {@link android.widget.ListView} containing the results of
37 * a query against the contacts content provider.  It uses a
38 * {@link android.content.CursorLoader} to manage the query on the provider.
39 *
40 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentListCursorLoader.java
41 *      fragment_cursor}
42 */
43public abstract class LoaderManager {
44    /**
45     * Callback interface for a client to interact with the manager.
46     */
47    public interface LoaderCallbacks<D> {
48        /**
49         * Instantiate and return a new Loader for the given ID.
50         *
51         * @param id The ID whose loader is to be created.
52         * @param args Any arguments supplied by the caller.
53         * @return Return a new Loader instance that is ready to start loading.
54         */
55        public Loader<D> onCreateLoader(int id, Bundle args);
56
57        /**
58         * Called when a previously created loader has finished its load.  Note
59         * that normally an application is <em>not</em> allowed to commit fragment
60         * transactions while in this call, since it can happen after an
61         * activity's state is saved.  See {@link FragmentManager#openTransaction()
62         * FragmentManager.openTransaction()} for further discussion on this.
63         *
64         * <p>This function is guaranteed to be called prior to the release of
65         * the last data that was supplied for this Loader.  At this point
66         * you should remove all use of the old data (since it will be released
67         * soon), but should not do your own release of the data since its Loader
68         * owns it and will take care of that.  The Loader will take care of
69         * management of its data so you don't have to.  In particular:
70         *
71         * <ul>
72         * <li> <p>The Loader will monitor for changes to the data, and report
73         * them to you through new calls here.  You should not monitor the
74         * data yourself.  For example, if the data is a {@link android.database.Cursor}
75         * and you place it in a {@link android.widget.CursorAdapter}, use
76         * the {@link android.widget.CursorAdapter#CursorAdapter(android.content.Context,
77         * android.database.Cursor, int)} constructor <em>without</em> passing
78         * in either {@link android.widget.CursorAdapter#FLAG_AUTO_REQUERY}
79         * or {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER}
80         * (that is, use 0 for the flags argument).  This prevents the CursorAdapter
81         * from doing its own observing of the Cursor, which is not needed since
82         * when a change happens you will get a new Cursor throw another call
83         * here.
84         * <li> The Loader will release the data once it knows the application
85         * is no longer using it.  For example, if the data is
86         * a {@link android.database.Cursor} from a {@link android.content.CursorLoader},
87         * you should not call close() on it yourself.  If the Cursor is being placed in a
88         * {@link android.widget.CursorAdapter}, you should use the
89         * {@link android.widget.CursorAdapter#swapCursor(android.database.Cursor)}
90         * method so that the old Cursor is not closed.
91         * </ul>
92         *
93         * @param loader The Loader that has finished.
94         * @param data The data generated by the Loader.
95         */
96        public void onLoadFinished(Loader<D> loader, D data);
97
98        /**
99         * Called when a previously created loader is being reset, and thus
100         * making its data unavailable.  The application should at this point
101         * remove any references it has to the Loader's data.
102         *
103         * @param loader The Loader that is being reset.
104         */
105        public void onLoaderReset(Loader<D> loader);
106    }
107
108    /**
109     * Ensures a loader is initialized and active.  If the loader doesn't
110     * already exist, one is created and (if the activity/fragment is currently
111     * started) starts the loader.  Otherwise the last created
112     * loader is re-used.
113     *
114     * <p>In either case, the given callback is associated with the loader, and
115     * will be called as the loader state changes.  If at the point of call
116     * the caller is in its started state, and the requested loader
117     * already exists and has generated its data, then
118     * callback {@link LoaderCallbacks#onLoadFinished} will
119     * be called immediately (inside of this function), so you must be prepared
120     * for this to happen.
121     *
122     * @param id A unique identifier for this loader.  Can be whatever you want.
123     * Identifiers are scoped to a particular LoaderManager instance.
124     * @param args Optional arguments to supply to the loader at construction.
125     * @param callback Interface the LoaderManager will call to report about
126     * changes in the state of the loader.  Required.
127     */
128    public abstract <D> Loader<D> initLoader(int id, Bundle args,
129            LoaderManager.LoaderCallbacks<D> callback);
130
131    /**
132     * Starts a new or restarts an existing {@link android.content.Loader} in
133     * this manager, registers the callbacks to it,
134     * and (if the activity/fragment is currently started) starts loading it.
135     * If a loader with the same id has previously been
136     * started it will automatically be destroyed when the new loader completes
137     * its work. The callback will be delivered before the old loader
138     * is destroyed.
139     *
140     * @param id A unique identifier for this loader.  Can be whatever you want.
141     * Identifiers are scoped to a particular LoaderManager instance.
142     * @param args Optional arguments to supply to the loader at construction.
143     * @param callback Interface the LoaderManager will call to report about
144     * changes in the state of the loader.  Required.
145     */
146    public abstract <D> Loader<D> restartLoader(int id, Bundle args,
147            LoaderManager.LoaderCallbacks<D> callback);
148
149    /**
150     * Stops and removes the loader with the given ID.  If this loader
151     * had previously reported data to the client through
152     * {@link LoaderCallbacks#onLoadFinished(Loader, Object)}, a call
153     * will be made to {@link LoaderCallbacks#onLoaderReset(Loader)}.
154     */
155    public abstract void destroyLoader(int id);
156
157    /**
158     * @deprecated Renamed to {@link #destroyLoader}.
159     */
160    @Deprecated
161    public void stopLoader(int id) {
162        destroyLoader(id);
163    }
164
165    /**
166     * Return the Loader with the given id or null if no matching Loader
167     * is found.
168     */
169    public abstract <D> Loader<D> getLoader(int id);
170
171    /**
172     * Print the LoaderManager's state into the given stream.
173     *
174     * @param prefix Text to print at the front of each line.
175     * @param fd The raw file descriptor that the dump is being sent to.
176     * @param writer A PrintWriter to which the dump is to be set.
177     * @param args Additional arguments to the dump request.
178     */
179    public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args);
180}
181
182class LoaderManagerImpl extends LoaderManager {
183    static final String TAG = "LoaderManagerImpl";
184    static final boolean DEBUG = true;
185
186    // These are the currently active loaders.  A loader is here
187    // from the time its load is started until it has been explicitly
188    // stopped or restarted by the application.
189    final SparseArray<LoaderInfo> mLoaders = new SparseArray<LoaderInfo>();
190
191    // These are previously run loaders.  This list is maintained internally
192    // to avoid destroying a loader while an application is still using it.
193    // It allows an application to restart a loader, but continue using its
194    // previously run loader until the new loader's data is available.
195    final SparseArray<LoaderInfo> mInactiveLoaders = new SparseArray<LoaderInfo>();
196
197    Activity mActivity;
198    boolean mStarted;
199    boolean mRetaining;
200    boolean mRetainingStarted;
201
202    final class LoaderInfo implements Loader.OnLoadCompleteListener<Object> {
203        final int mId;
204        final Bundle mArgs;
205        LoaderManager.LoaderCallbacks<Object> mCallbacks;
206        Loader<Object> mLoader;
207        Object mData;
208        boolean mStarted;
209        boolean mNeedReset;
210        boolean mRetaining;
211        boolean mRetainingStarted;
212        boolean mDestroyed;
213        boolean mListenerRegistered;
214
215        public LoaderInfo(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callbacks) {
216            mId = id;
217            mArgs = args;
218            mCallbacks = callbacks;
219        }
220
221        void start() {
222            if (mRetaining && mRetainingStarted) {
223                // Our owner is started, but we were being retained from a
224                // previous instance in the started state...  so there is really
225                // nothing to do here, since the loaders are still started.
226                mStarted = true;
227                return;
228            }
229
230            if (mStarted) {
231                // If loader already started, don't restart.
232                return;
233            }
234
235            if (DEBUG) Log.v(TAG, "  Starting: " + this);
236            if (mLoader == null && mCallbacks != null) {
237               mLoader = mCallbacks.onCreateLoader(mId, mArgs);
238            }
239            if (mLoader != null) {
240                if (!mListenerRegistered) {
241                    mLoader.registerListener(mId, this);
242                    mListenerRegistered = true;
243                }
244                mLoader.startLoading();
245                mStarted = true;
246            }
247        }
248
249        void retain() {
250            if (DEBUG) Log.v(TAG, "  Retaining: " + this);
251            mRetaining = true;
252            mRetainingStarted = mStarted;
253            mStarted = false;
254            mCallbacks = null;
255        }
256
257        void finishRetain() {
258            if (mRetaining) {
259                if (DEBUG) Log.v(TAG, "  Finished Retaining: " + this);
260                mRetaining = false;
261                if (mStarted != mRetainingStarted) {
262                    if (!mStarted) {
263                        // This loader was retained in a started state, but
264                        // at the end of retaining everything our owner is
265                        // no longer started...  so make it stop.
266                        stop();
267                    }
268                }
269            }
270
271            if (mStarted && mData != null) {
272                // This loader has retained its data, either completely across
273                // a configuration change or just whatever the last data set
274                // was after being restarted from a stop, and now at the point of
275                // finishing the retain we find we remain started, have
276                // our data, and the owner has a new callback...  so
277                // let's deliver the data now.
278                callOnLoadFinished(mLoader, mData);
279            }
280        }
281
282        void stop() {
283            if (DEBUG) Log.v(TAG, "  Stopping: " + this);
284            mStarted = false;
285            if (!mRetaining) {
286                if (mLoader != null && mListenerRegistered) {
287                    // Let the loader know we're done with it
288                    mListenerRegistered = false;
289                    mLoader.unregisterListener(this);
290                    mLoader.stopLoading();
291                }
292            }
293        }
294
295        void destroy() {
296            if (DEBUG) Log.v(TAG, "  Destroying: " + this);
297            mDestroyed = true;
298            if (mCallbacks != null && mLoader != null && mData != null && mNeedReset) {
299                String lastBecause = null;
300                if (mActivity != null) {
301                    lastBecause = mActivity.mFragments.mNoTransactionsBecause;
302                    mActivity.mFragments.mNoTransactionsBecause = "onLoaderReset";
303                }
304                try {
305                    mCallbacks.onLoaderReset(mLoader);
306                } finally {
307                    if (mActivity != null) {
308                        mActivity.mFragments.mNoTransactionsBecause = lastBecause;
309                    }
310                }
311            }
312            mNeedReset = false;
313            mCallbacks = null;
314            mData = null;
315            if (mLoader != null) {
316                if (mListenerRegistered) {
317                    mListenerRegistered = false;
318                    mLoader.unregisterListener(this);
319                }
320                mLoader.reset();
321            }
322        }
323
324        @Override public void onLoadComplete(Loader<Object> loader, Object data) {
325            if (DEBUG) Log.v(TAG, "onLoadComplete: " + this + " mDestroyed=" + mDestroyed);
326
327            if (mDestroyed) {
328                return;
329            }
330
331            // Notify of the new data so the app can switch out the old data before
332            // we try to destroy it.
333            mData = data;
334            if (mStarted) {
335                callOnLoadFinished(loader, data);
336            }
337
338            if (DEBUG) Log.v(TAG, "onLoadFinished returned: " + this);
339
340            // We have now given the application the new loader with its
341            // loaded data, so it should have stopped using the previous
342            // loader.  If there is a previous loader on the inactive list,
343            // clean it up.
344            LoaderInfo info = mInactiveLoaders.get(mId);
345            if (info != null && info != this) {
346                info.mNeedReset = false;
347                info.destroy();
348                mInactiveLoaders.remove(mId);
349            }
350        }
351
352        void callOnLoadFinished(Loader<Object> loader, Object data) {
353            if (mCallbacks != null) {
354                String lastBecause = null;
355                if (mActivity != null) {
356                    lastBecause = mActivity.mFragments.mNoTransactionsBecause;
357                    mActivity.mFragments.mNoTransactionsBecause = "onLoadFinished";
358                }
359                try {
360                    mCallbacks.onLoadFinished(loader, data);
361                } finally {
362                    if (mActivity != null) {
363                        mActivity.mFragments.mNoTransactionsBecause = lastBecause;
364                    }
365                }
366                mNeedReset = true;
367            }
368        }
369
370        @Override
371        public String toString() {
372            StringBuilder sb = new StringBuilder(64);
373            sb.append("LoaderInfo{");
374            sb.append(Integer.toHexString(System.identityHashCode(this)));
375            sb.append(" #");
376            sb.append(mId);
377            if (mArgs != null) {
378                sb.append(" ");
379                sb.append(mArgs.toString());
380            }
381            sb.append("}");
382            return sb.toString();
383        }
384
385        public String toBasicString() {
386            StringBuilder sb = new StringBuilder(64);
387            sb.append("LoaderInfo{");
388            sb.append(Integer.toHexString(System.identityHashCode(this)));
389            sb.append(" #");
390            sb.append(mId);
391            sb.append("}");
392            return sb.toString();
393        }
394
395        public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
396            writer.print(prefix); writer.print("mId="); writer.print(mId);
397                    writer.print(" mArgs="); writer.println(mArgs);
398            writer.print(prefix); writer.print("mCallbacks="); writer.println(mCallbacks);
399            writer.print(prefix); writer.print("mLoader="); writer.println(mLoader);
400            writer.print(prefix); writer.print("mData="); writer.println(mData);
401            writer.print(prefix); writer.print("mStarted="); writer.print(mStarted);
402                    writer.print(" mRetaining="); writer.print(mRetaining);
403                    writer.print(" mDestroyed="); writer.println(mDestroyed);
404            writer.print(prefix); writer.print("mNeedReset="); writer.print(mNeedReset);
405                    writer.print(" mListenerRegistered="); writer.println(mListenerRegistered);
406        }
407    }
408
409    LoaderManagerImpl(Activity activity, boolean started) {
410        mActivity = activity;
411        mStarted = started;
412    }
413
414    void updateActivity(Activity activity) {
415        mActivity = activity;
416    }
417
418    private LoaderInfo createLoader(int id, Bundle args,
419            LoaderManager.LoaderCallbacks<Object> callback) {
420        LoaderInfo info = new LoaderInfo(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
421        mLoaders.put(id, info);
422        Loader<Object> loader = callback.onCreateLoader(id, args);
423        info.mLoader = (Loader<Object>)loader;
424        if (mStarted) {
425            // The activity will start all existing loaders in it's onStart(),
426            // so only start them here if we're past that point of the activitiy's
427            // life cycle
428            info.start();
429        }
430        return info;
431    }
432
433    @SuppressWarnings("unchecked")
434    public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
435        LoaderInfo info = mLoaders.get(id);
436
437        if (DEBUG) Log.v(TAG, "initLoader in " + this + ": cur=" + info);
438
439        if (info == null) {
440            // Loader doesn't already exist; create.
441            info = createLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
442        } else {
443            info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
444        }
445
446        if (info.mData != null && mStarted) {
447            // If the loader has already generated its data, report it now.
448            info.callOnLoadFinished(info.mLoader, info.mData);
449        }
450
451        return (Loader<D>)info.mLoader;
452    }
453
454    @SuppressWarnings("unchecked")
455    public <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
456        LoaderInfo info = mLoaders.get(id);
457        if (DEBUG) Log.v(TAG, "restartLoader in " + this + ": cur=" + info);
458        if (info != null) {
459            LoaderInfo inactive = mInactiveLoaders.get(id);
460            if (inactive != null) {
461                if (info.mData != null) {
462                    // This loader now has data...  we are probably being
463                    // called from within onLoadComplete, where we haven't
464                    // yet destroyed the last inactive loader.  So just do
465                    // that now.
466                    if (DEBUG) Log.v(TAG, "  Removing last inactive loader in " + this);
467                    inactive.mNeedReset = false;
468                    inactive.destroy();
469                    mInactiveLoaders.put(id, info);
470                } else {
471                    // We already have an inactive loader for this ID that we are
472                    // waiting for!  Now we have three active loaders... let's just
473                    // drop the one in the middle, since we are still waiting for
474                    // its result but that result is already out of date.
475                    if (DEBUG) Log.v(TAG, "  Removing intermediate loader in " + this);
476                    info.destroy();
477                }
478            } else {
479                // Keep track of the previous instance of this loader so we can destroy
480                // it when the new one completes.
481                if (DEBUG) Log.v(TAG, "  Making inactive: " + info);
482                mInactiveLoaders.put(id, info);
483            }
484        }
485
486        info = createLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
487        return (Loader<D>)info.mLoader;
488    }
489
490    public void destroyLoader(int id) {
491        if (DEBUG) Log.v(TAG, "stopLoader in " + this + " of " + id);
492        int idx = mLoaders.indexOfKey(id);
493        if (idx >= 0) {
494            LoaderInfo info = mLoaders.valueAt(idx);
495            mLoaders.removeAt(idx);
496            info.destroy();
497        }
498        idx = mInactiveLoaders.indexOfKey(id);
499        if (idx >= 0) {
500            LoaderInfo info = mInactiveLoaders.valueAt(idx);
501            mInactiveLoaders.removeAt(idx);
502            info.destroy();
503        }
504    }
505
506    @SuppressWarnings("unchecked")
507    public <D> Loader<D> getLoader(int id) {
508        LoaderInfo loaderInfo = mLoaders.get(id);
509        if (loaderInfo != null) {
510            return (Loader<D>)mLoaders.get(id).mLoader;
511        }
512        return null;
513    }
514
515    void doStart() {
516        if (DEBUG) Log.v(TAG, "Starting: " + this);
517        if (mStarted) {
518            RuntimeException e = new RuntimeException("here");
519            e.fillInStackTrace();
520            Log.w(TAG, "Called doStart when already started: " + this, e);
521            return;
522        }
523
524        mStarted = true;
525
526        // Call out to sub classes so they can start their loaders
527        // Let the existing loaders know that we want to be notified when a load is complete
528        for (int i = mLoaders.size()-1; i >= 0; i--) {
529            mLoaders.valueAt(i).start();
530        }
531    }
532
533    void doStop() {
534        if (DEBUG) Log.v(TAG, "Stopping: " + this);
535        if (!mStarted) {
536            RuntimeException e = new RuntimeException("here");
537            e.fillInStackTrace();
538            Log.w(TAG, "Called doStop when not started: " + this, e);
539            return;
540        }
541
542        for (int i = mLoaders.size()-1; i >= 0; i--) {
543            mLoaders.valueAt(i).stop();
544        }
545        mStarted = false;
546    }
547
548    void doRetain() {
549        if (DEBUG) Log.v(TAG, "Retaining: " + this);
550        if (!mStarted) {
551            RuntimeException e = new RuntimeException("here");
552            e.fillInStackTrace();
553            Log.w(TAG, "Called doRetain when not started: " + this, e);
554            return;
555        }
556
557        mRetaining = true;
558        mStarted = false;
559        for (int i = mLoaders.size()-1; i >= 0; i--) {
560            mLoaders.valueAt(i).retain();
561        }
562    }
563
564    void finishRetain() {
565        if (DEBUG) Log.v(TAG, "Finished Retaining: " + this);
566
567        mRetaining = false;
568        for (int i = mLoaders.size()-1; i >= 0; i--) {
569            mLoaders.valueAt(i).finishRetain();
570        }
571    }
572
573    void doDestroy() {
574        if (!mRetaining) {
575            if (DEBUG) Log.v(TAG, "Destroying Active: " + this);
576            for (int i = mLoaders.size()-1; i >= 0; i--) {
577                mLoaders.valueAt(i).destroy();
578            }
579        }
580
581        if (DEBUG) Log.v(TAG, "Destroying Inactive: " + this);
582        for (int i = mInactiveLoaders.size()-1; i >= 0; i--) {
583            mInactiveLoaders.valueAt(i).destroy();
584        }
585        mInactiveLoaders.clear();
586    }
587
588    @Override
589    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
590        if (mLoaders.size() > 0) {
591            writer.print(prefix); writer.println("Active Loaders:");
592            String innerPrefix = prefix + "    ";
593            for (int i=0; i < mLoaders.size(); i++) {
594                LoaderInfo li = mLoaders.valueAt(i);
595                writer.print(prefix); writer.print("  #"); writer.print(mLoaders.keyAt(i));
596                        writer.print(": "); writer.println(li.toBasicString());
597                li.dump(innerPrefix, fd, writer, args);
598            }
599        }
600        if (mInactiveLoaders.size() > 0) {
601            writer.print(prefix); writer.println("Inactive Loaders:");
602            String innerPrefix = prefix + "    ";
603            for (int i=0; i < mInactiveLoaders.size(); i++) {
604                LoaderInfo li = mInactiveLoaders.valueAt(i);
605                writer.print(prefix); writer.print("  #"); writer.print(mInactiveLoaders.keyAt(i));
606                        writer.print(": "); writer.println(li.toBasicString());
607                li.dump(innerPrefix, fd, writer, args);
608            }
609        }
610    }
611}
612