LoaderManager.java revision 37510908a7b570accb2c4829842790b3d9d3a102
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.DebugUtils;
22import android.util.Log;
23import android.util.SparseArray;
24
25import java.io.FileDescriptor;
26import java.io.PrintWriter;
27import java.lang.reflect.Modifier;
28
29/**
30 * Interface associated with an {@link Activity} or {@link Fragment} for managing
31 * one or more {@link android.content.Loader} instances associated with it.  This
32 * helps an application manage longer-running operations in conjunction with the
33 * Activity or Fragment lifecycle; the most common use of this is with a
34 * {@link android.content.CursorLoader}, however applications are free to write
35 * their own loaders for loading other types of data.
36 *
37 * While the LoaderManager API was introduced in
38 * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, a version of the API
39 * is also available for use on older platforms.  See the blog post
40 * <a href="http://android-developers.blogspot.com/2011/03/fragments-for-all.html">
41 * Fragments For All</a> for more details.
42 *
43 * <p>As an example, here is the full implementation of a {@link Fragment}
44 * that displays a {@link android.widget.ListView} containing the results of
45 * a query against the contacts content provider.  It uses a
46 * {@link android.content.CursorLoader} to manage the query on the provider.
47 *
48 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LoaderCursor.java
49 *      fragment_cursor}
50 *
51 * <div class="special reference">
52 * <h3>Developer Guides</h3>
53 * <p>For more information about using loaders, read the
54 * <a href="{@docRoot}guide/topics/fundamentals/loaders.html">Loaders</a> developer guide.</p>
55 * </div>
56 */
57public abstract class LoaderManager {
58    /**
59     * Callback interface for a client to interact with the manager.
60     */
61    public interface LoaderCallbacks<D> {
62        /**
63         * Instantiate and return a new Loader for the given ID.
64         *
65         * @param id The ID whose loader is to be created.
66         * @param args Any arguments supplied by the caller.
67         * @return Return a new Loader instance that is ready to start loading.
68         */
69        public Loader<D> onCreateLoader(int id, Bundle args);
70
71        /**
72         * Called when a previously created loader has finished its load.  Note
73         * that normally an application is <em>not</em> allowed to commit fragment
74         * transactions while in this call, since it can happen after an
75         * activity's state is saved.  See {@link FragmentManager#beginTransaction()
76         * FragmentManager.openTransaction()} for further discussion on this.
77         *
78         * <p>This function is guaranteed to be called prior to the release of
79         * the last data that was supplied for this Loader.  At this point
80         * you should remove all use of the old data (since it will be released
81         * soon), but should not do your own release of the data since its Loader
82         * owns it and will take care of that.  The Loader will take care of
83         * management of its data so you don't have to.  In particular:
84         *
85         * <ul>
86         * <li> <p>The Loader will monitor for changes to the data, and report
87         * them to you through new calls here.  You should not monitor the
88         * data yourself.  For example, if the data is a {@link android.database.Cursor}
89         * and you place it in a {@link android.widget.CursorAdapter}, use
90         * the {@link android.widget.CursorAdapter#CursorAdapter(android.content.Context,
91         * android.database.Cursor, int)} constructor <em>without</em> passing
92         * in either {@link android.widget.CursorAdapter#FLAG_AUTO_REQUERY}
93         * or {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER}
94         * (that is, use 0 for the flags argument).  This prevents the CursorAdapter
95         * from doing its own observing of the Cursor, which is not needed since
96         * when a change happens you will get a new Cursor throw another call
97         * here.
98         * <li> The Loader will release the data once it knows the application
99         * is no longer using it.  For example, if the data is
100         * a {@link android.database.Cursor} from a {@link android.content.CursorLoader},
101         * you should not call close() on it yourself.  If the Cursor is being placed in a
102         * {@link android.widget.CursorAdapter}, you should use the
103         * {@link android.widget.CursorAdapter#swapCursor(android.database.Cursor)}
104         * method so that the old Cursor is not closed.
105         * </ul>
106         *
107         * @param loader The Loader that has finished.
108         * @param data The data generated by the Loader.
109         */
110        public void onLoadFinished(Loader<D> loader, D data);
111
112        /**
113         * Called when a previously created loader is being reset, and thus
114         * making its data unavailable.  The application should at this point
115         * remove any references it has to the Loader's data.
116         *
117         * @param loader The Loader that is being reset.
118         */
119        public void onLoaderReset(Loader<D> loader);
120    }
121
122    /**
123     * Ensures a loader is initialized and active.  If the loader doesn't
124     * already exist, one is created and (if the activity/fragment is currently
125     * started) starts the loader.  Otherwise the last created
126     * loader is re-used.
127     *
128     * <p>In either case, the given callback is associated with the loader, and
129     * will be called as the loader state changes.  If at the point of call
130     * the caller is in its started state, and the requested loader
131     * already exists and has generated its data, then
132     * callback {@link LoaderCallbacks#onLoadFinished} will
133     * be called immediately (inside of this function), so you must be prepared
134     * for this to happen.
135     *
136     * @param id A unique identifier for this loader.  Can be whatever you want.
137     * Identifiers are scoped to a particular LoaderManager instance.
138     * @param args Optional arguments to supply to the loader at construction.
139     * If a loader already exists (a new one does not need to be created), this
140     * parameter will be ignored and the last arguments continue to be used.
141     * @param callback Interface the LoaderManager will call to report about
142     * changes in the state of the loader.  Required.
143     */
144    public abstract <D> Loader<D> initLoader(int id, Bundle args,
145            LoaderManager.LoaderCallbacks<D> callback);
146
147    /**
148     * Starts a new or restarts an existing {@link android.content.Loader} in
149     * this manager, registers the callbacks to it,
150     * and (if the activity/fragment is currently started) starts loading it.
151     * If a loader with the same id has previously been
152     * started it will automatically be destroyed when the new loader completes
153     * its work. The callback will be delivered before the old loader
154     * is destroyed.
155     *
156     * @param id A unique identifier for this loader.  Can be whatever you want.
157     * Identifiers are scoped to a particular LoaderManager instance.
158     * @param args Optional arguments to supply to the loader at construction.
159     * @param callback Interface the LoaderManager will call to report about
160     * changes in the state of the loader.  Required.
161     */
162    public abstract <D> Loader<D> restartLoader(int id, Bundle args,
163            LoaderManager.LoaderCallbacks<D> callback);
164
165    /**
166     * Stops and removes the loader with the given ID.  If this loader
167     * had previously reported data to the client through
168     * {@link LoaderCallbacks#onLoadFinished(Loader, Object)}, a call
169     * will be made to {@link LoaderCallbacks#onLoaderReset(Loader)}.
170     */
171    public abstract void destroyLoader(int id);
172
173    /**
174     * Return the Loader with the given id or null if no matching Loader
175     * is found.
176     */
177    public abstract <D> Loader<D> getLoader(int id);
178
179    /**
180     * Print the LoaderManager's state into the given stream.
181     *
182     * @param prefix Text to print at the front of each line.
183     * @param fd The raw file descriptor that the dump is being sent to.
184     * @param writer A PrintWriter to which the dump is to be set.
185     * @param args Additional arguments to the dump request.
186     */
187    public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args);
188
189    /**
190     * Control whether the framework's internal loader manager debugging
191     * logs are turned on.  If enabled, you will see output in logcat as
192     * the framework performs loader operations.
193     */
194    public static void enableDebugLogging(boolean enabled) {
195        LoaderManagerImpl.DEBUG = enabled;
196    }
197}
198
199class LoaderManagerImpl extends LoaderManager {
200    static final String TAG = "LoaderManager";
201    static boolean DEBUG = false;
202
203    // These are the currently active loaders.  A loader is here
204    // from the time its load is started until it has been explicitly
205    // stopped or restarted by the application.
206    final SparseArray<LoaderInfo> mLoaders = new SparseArray<LoaderInfo>();
207
208    // These are previously run loaders.  This list is maintained internally
209    // to avoid destroying a loader while an application is still using it.
210    // It allows an application to restart a loader, but continue using its
211    // previously run loader until the new loader's data is available.
212    final SparseArray<LoaderInfo> mInactiveLoaders = new SparseArray<LoaderInfo>();
213
214    Activity mActivity;
215    boolean mStarted;
216    boolean mRetaining;
217    boolean mRetainingStarted;
218
219    boolean mCreatingLoader;
220
221    final class LoaderInfo implements Loader.OnLoadCompleteListener<Object> {
222        final int mId;
223        final Bundle mArgs;
224        LoaderManager.LoaderCallbacks<Object> mCallbacks;
225        Loader<Object> mLoader;
226        boolean mHaveData;
227        boolean mDeliveredData;
228        Object mData;
229        boolean mStarted;
230        boolean mRetaining;
231        boolean mRetainingStarted;
232        boolean mReportNextStart;
233        boolean mDestroyed;
234        boolean mListenerRegistered;
235
236        LoaderInfo mPendingLoader;
237
238        public LoaderInfo(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callbacks) {
239            mId = id;
240            mArgs = args;
241            mCallbacks = callbacks;
242        }
243
244        void start() {
245            if (mRetaining && mRetainingStarted) {
246                // Our owner is started, but we were being retained from a
247                // previous instance in the started state...  so there is really
248                // nothing to do here, since the loaders are still started.
249                mStarted = true;
250                return;
251            }
252
253            if (mStarted) {
254                // If loader already started, don't restart.
255                return;
256            }
257
258            mStarted = true;
259
260            if (DEBUG) Log.v(TAG, "  Starting: " + this);
261            if (mLoader == null && mCallbacks != null) {
262               mLoader = mCallbacks.onCreateLoader(mId, mArgs);
263            }
264            if (mLoader != null) {
265                if (mLoader.getClass().isMemberClass()
266                        && !Modifier.isStatic(mLoader.getClass().getModifiers())) {
267                    throw new IllegalArgumentException(
268                            "Object returned from onCreateLoader must not be a non-static inner member class: "
269                            + mLoader);
270                }
271                if (!mListenerRegistered) {
272                    mLoader.registerListener(mId, this);
273                    mListenerRegistered = true;
274                }
275                mLoader.startLoading();
276            }
277        }
278
279        void retain() {
280            if (DEBUG) Log.v(TAG, "  Retaining: " + this);
281            mRetaining = true;
282            mRetainingStarted = mStarted;
283            mStarted = false;
284            mCallbacks = null;
285        }
286
287        void finishRetain() {
288            if (mRetaining) {
289                if (DEBUG) Log.v(TAG, "  Finished Retaining: " + this);
290                mRetaining = false;
291                if (mStarted != mRetainingStarted) {
292                    if (!mStarted) {
293                        // This loader was retained in a started state, but
294                        // at the end of retaining everything our owner is
295                        // no longer started...  so make it stop.
296                        stop();
297                    }
298                }
299            }
300
301            if (mStarted && mHaveData && !mReportNextStart) {
302                // This loader has retained its data, either completely across
303                // a configuration change or just whatever the last data set
304                // was after being restarted from a stop, and now at the point of
305                // finishing the retain we find we remain started, have
306                // our data, and the owner has a new callback...  so
307                // let's deliver the data now.
308                callOnLoadFinished(mLoader, mData);
309            }
310        }
311
312        void reportStart() {
313            if (mStarted) {
314                if (mReportNextStart) {
315                    mReportNextStart = false;
316                    if (mHaveData) {
317                        callOnLoadFinished(mLoader, mData);
318                    }
319                }
320            }
321        }
322
323        void stop() {
324            if (DEBUG) Log.v(TAG, "  Stopping: " + this);
325            mStarted = false;
326            if (!mRetaining) {
327                if (mLoader != null && mListenerRegistered) {
328                    // Let the loader know we're done with it
329                    mListenerRegistered = false;
330                    mLoader.unregisterListener(this);
331                    mLoader.stopLoading();
332                }
333            }
334        }
335
336        void destroy() {
337            if (DEBUG) Log.v(TAG, "  Destroying: " + this);
338            mDestroyed = true;
339            boolean needReset = mDeliveredData;
340            mDeliveredData = false;
341            if (mCallbacks != null && mLoader != null && mHaveData && needReset) {
342                if (DEBUG) Log.v(TAG, "  Reseting: " + this);
343                String lastBecause = null;
344                if (mActivity != null) {
345                    lastBecause = mActivity.mFragments.mNoTransactionsBecause;
346                    mActivity.mFragments.mNoTransactionsBecause = "onLoaderReset";
347                }
348                try {
349                    mCallbacks.onLoaderReset(mLoader);
350                } finally {
351                    if (mActivity != null) {
352                        mActivity.mFragments.mNoTransactionsBecause = lastBecause;
353                    }
354                }
355            }
356            mCallbacks = null;
357            mData = null;
358            mHaveData = false;
359            if (mLoader != null) {
360                if (mListenerRegistered) {
361                    mListenerRegistered = false;
362                    mLoader.unregisterListener(this);
363                }
364                mLoader.reset();
365            }
366            if (mPendingLoader != null) {
367                mPendingLoader.destroy();
368            }
369        }
370
371        @Override public void onLoadComplete(Loader<Object> loader, Object data) {
372            if (DEBUG) Log.v(TAG, "onLoadComplete: " + this);
373
374            if (mDestroyed) {
375                if (DEBUG) Log.v(TAG, "  Ignoring load complete -- destroyed");
376                return;
377            }
378
379            if (mLoaders.get(mId) != this) {
380                // This data is not coming from the current active loader.
381                // We don't care about it.
382                if (DEBUG) Log.v(TAG, "  Ignoring load complete -- not active");
383                return;
384            }
385
386            LoaderInfo pending = mPendingLoader;
387            if (pending != null) {
388                // There is a new request pending and we were just
389                // waiting for the old one to complete before starting
390                // it.  So now it is time, switch over to the new loader.
391                if (DEBUG) Log.v(TAG, "  Switching to pending loader: " + pending);
392                mPendingLoader = null;
393                mLoaders.put(mId, null);
394                destroy();
395                installLoader(pending);
396                return;
397            }
398
399            // Notify of the new data so the app can switch out the old data before
400            // we try to destroy it.
401            if (mData != data || !mHaveData) {
402                mData = data;
403                mHaveData = true;
404                if (mStarted) {
405                    callOnLoadFinished(loader, data);
406                }
407            }
408
409            //if (DEBUG) Log.v(TAG, "  onLoadFinished returned: " + this);
410
411            // We have now given the application the new loader with its
412            // loaded data, so it should have stopped using the previous
413            // loader.  If there is a previous loader on the inactive list,
414            // clean it up.
415            LoaderInfo info = mInactiveLoaders.get(mId);
416            if (info != null && info != this) {
417                info.mDeliveredData = false;
418                info.destroy();
419                mInactiveLoaders.remove(mId);
420            }
421
422            if (mActivity != null && !hasRunningLoaders()) {
423                mActivity.mFragments.startPendingDeferredFragments();
424            }
425        }
426
427        void callOnLoadFinished(Loader<Object> loader, Object data) {
428            if (mCallbacks != null) {
429                String lastBecause = null;
430                if (mActivity != null) {
431                    lastBecause = mActivity.mFragments.mNoTransactionsBecause;
432                    mActivity.mFragments.mNoTransactionsBecause = "onLoadFinished";
433                }
434                try {
435                    if (DEBUG) Log.v(TAG, "  onLoadFinished in " + loader + ": "
436                            + loader.dataToString(data));
437                    mCallbacks.onLoadFinished(loader, data);
438                } finally {
439                    if (mActivity != null) {
440                        mActivity.mFragments.mNoTransactionsBecause = lastBecause;
441                    }
442                }
443                mDeliveredData = true;
444            }
445        }
446
447        @Override
448        public String toString() {
449            StringBuilder sb = new StringBuilder(64);
450            sb.append("LoaderInfo{");
451            sb.append(Integer.toHexString(System.identityHashCode(this)));
452            sb.append(" #");
453            sb.append(mId);
454            sb.append(" : ");
455            DebugUtils.buildShortClassTag(mLoader, sb);
456            sb.append("}}");
457            return sb.toString();
458        }
459
460        public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
461            writer.print(prefix); writer.print("mId="); writer.print(mId);
462                    writer.print(" mArgs="); writer.println(mArgs);
463            writer.print(prefix); writer.print("mCallbacks="); writer.println(mCallbacks);
464            writer.print(prefix); writer.print("mLoader="); writer.println(mLoader);
465            if (mLoader != null) {
466                mLoader.dump(prefix + "  ", fd, writer, args);
467            }
468            if (mHaveData || mDeliveredData) {
469                writer.print(prefix); writer.print("mHaveData="); writer.print(mHaveData);
470                        writer.print("  mDeliveredData="); writer.println(mDeliveredData);
471                writer.print(prefix); writer.print("mData="); writer.println(mData);
472            }
473            writer.print(prefix); writer.print("mStarted="); writer.print(mStarted);
474                    writer.print(" mReportNextStart="); writer.print(mReportNextStart);
475                    writer.print(" mDestroyed="); writer.println(mDestroyed);
476            writer.print(prefix); writer.print("mRetaining="); writer.print(mRetaining);
477                    writer.print(" mRetainingStarted="); writer.print(mRetainingStarted);
478                    writer.print(" mListenerRegistered="); writer.println(mListenerRegistered);
479            if (mPendingLoader != null) {
480                writer.print(prefix); writer.println("Pending Loader ");
481                        writer.print(mPendingLoader); writer.println(":");
482                mPendingLoader.dump(prefix + "  ", fd, writer, args);
483            }
484        }
485    }
486
487    LoaderManagerImpl(Activity activity, boolean started) {
488        mActivity = activity;
489        mStarted = started;
490    }
491
492    void updateActivity(Activity activity) {
493        mActivity = activity;
494    }
495
496    private LoaderInfo createLoader(int id, Bundle args,
497            LoaderManager.LoaderCallbacks<Object> callback) {
498        LoaderInfo info = new LoaderInfo(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
499        Loader<Object> loader = callback.onCreateLoader(id, args);
500        info.mLoader = (Loader<Object>)loader;
501        return info;
502    }
503
504    private LoaderInfo createAndInstallLoader(int id, Bundle args,
505            LoaderManager.LoaderCallbacks<Object> callback) {
506        try {
507            mCreatingLoader = true;
508            LoaderInfo info = createLoader(id, args, callback);
509            installLoader(info);
510            return info;
511        } finally {
512            mCreatingLoader = false;
513        }
514    }
515
516    void installLoader(LoaderInfo info) {
517        mLoaders.put(info.mId, info);
518        if (mStarted) {
519            // The activity will start all existing loaders in it's onStart(),
520            // so only start them here if we're past that point of the activitiy's
521            // life cycle
522            info.start();
523        }
524    }
525
526    /**
527     * Call to initialize a particular ID with a Loader.  If this ID already
528     * has a Loader associated with it, it is left unchanged and any previous
529     * callbacks replaced with the newly provided ones.  If there is not currently
530     * a Loader for the ID, a new one is created and started.
531     *
532     * <p>This function should generally be used when a component is initializing,
533     * to ensure that a Loader it relies on is created.  This allows it to re-use
534     * an existing Loader's data if there already is one, so that for example
535     * when an {@link Activity} is re-created after a configuration change it
536     * does not need to re-create its loaders.
537     *
538     * <p>Note that in the case where an existing Loader is re-used, the
539     * <var>args</var> given here <em>will be ignored</em> because you will
540     * continue using the previous Loader.
541     *
542     * @param id A unique (to this LoaderManager instance) identifier under
543     * which to manage the new Loader.
544     * @param args Optional arguments that will be propagated to
545     * {@link LoaderCallbacks#onCreateLoader(int, Bundle) LoaderCallbacks.onCreateLoader()}.
546     * @param callback Interface implementing management of this Loader.  Required.
547     * Its onCreateLoader() method will be called while inside of the function to
548     * instantiate the Loader object.
549     */
550    @SuppressWarnings("unchecked")
551    public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
552        if (mCreatingLoader) {
553            throw new IllegalStateException("Called while creating a loader");
554        }
555
556        LoaderInfo info = mLoaders.get(id);
557
558        if (DEBUG) Log.v(TAG, "initLoader in " + this + ": args=" + args);
559
560        if (info == null) {
561            // Loader doesn't already exist; create.
562            info = createAndInstallLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
563            if (DEBUG) Log.v(TAG, "  Created new loader " + info);
564        } else {
565            if (DEBUG) Log.v(TAG, "  Re-using existing loader " + info);
566            info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
567        }
568
569        if (info.mHaveData && mStarted) {
570            // If the loader has already generated its data, report it now.
571            info.callOnLoadFinished(info.mLoader, info.mData);
572        }
573
574        return (Loader<D>)info.mLoader;
575    }
576
577    /**
578     * Call to re-create the Loader associated with a particular ID.  If there
579     * is currently a Loader associated with this ID, it will be
580     * canceled/stopped/destroyed as appropriate.  A new Loader with the given
581     * arguments will be created and its data delivered to you once available.
582     *
583     * <p>This function does some throttling of Loaders.  If too many Loaders
584     * have been created for the given ID but not yet generated their data,
585     * new calls to this function will create and return a new Loader but not
586     * actually start it until some previous loaders have completed.
587     *
588     * <p>After calling this function, any previous Loaders associated with
589     * this ID will be considered invalid, and you will receive no further
590     * data updates from them.
591     *
592     * @param id A unique (to this LoaderManager instance) identifier under
593     * which to manage the new Loader.
594     * @param args Optional arguments that will be propagated to
595     * {@link LoaderCallbacks#onCreateLoader(int, Bundle) LoaderCallbacks.onCreateLoader()}.
596     * @param callback Interface implementing management of this Loader.  Required.
597     * Its onCreateLoader() method will be called while inside of the function to
598     * instantiate the Loader object.
599     */
600    @SuppressWarnings("unchecked")
601    public <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
602        if (mCreatingLoader) {
603            throw new IllegalStateException("Called while creating a loader");
604        }
605
606        LoaderInfo info = mLoaders.get(id);
607        if (DEBUG) Log.v(TAG, "restartLoader in " + this + ": args=" + args);
608        if (info != null) {
609            LoaderInfo inactive = mInactiveLoaders.get(id);
610            if (inactive != null) {
611                if (info.mHaveData) {
612                    // This loader now has data...  we are probably being
613                    // called from within onLoadComplete, where we haven't
614                    // yet destroyed the last inactive loader.  So just do
615                    // that now.
616                    if (DEBUG) Log.v(TAG, "  Removing last inactive loader: " + info);
617                    inactive.mDeliveredData = false;
618                    inactive.destroy();
619                    info.mLoader.abandon();
620                    mInactiveLoaders.put(id, info);
621                } else {
622                    // We already have an inactive loader for this ID that we are
623                    // waiting for!  What to do, what to do...
624                    if (!info.mStarted) {
625                        // The current Loader has not been started...  we thus
626                        // have no reason to keep it around, so bam, slam,
627                        // thank-you-ma'am.
628                        if (DEBUG) Log.v(TAG, "  Current loader is stopped; replacing");
629                        mLoaders.put(id, null);
630                        info.destroy();
631                    } else {
632                        // Now we have three active loaders... we'll queue
633                        // up this request to be processed once one of the other loaders
634                        // finishes.
635                        if (info.mPendingLoader != null) {
636                            if (DEBUG) Log.v(TAG, "  Removing pending loader: " + info.mPendingLoader);
637                            info.mPendingLoader.destroy();
638                            info.mPendingLoader = null;
639                        }
640                        if (DEBUG) Log.v(TAG, "  Enqueuing as new pending loader");
641                        info.mPendingLoader = createLoader(id, args,
642                                (LoaderManager.LoaderCallbacks<Object>)callback);
643                        return (Loader<D>)info.mPendingLoader.mLoader;
644                    }
645                }
646            } else {
647                // Keep track of the previous instance of this loader so we can destroy
648                // it when the new one completes.
649                if (DEBUG) Log.v(TAG, "  Making last loader inactive: " + info);
650                info.mLoader.abandon();
651                mInactiveLoaders.put(id, info);
652            }
653        }
654
655        info = createAndInstallLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
656        return (Loader<D>)info.mLoader;
657    }
658
659    /**
660     * Rip down, tear apart, shred to pieces a current Loader ID.  After returning
661     * from this function, any Loader objects associated with this ID are
662     * destroyed.  Any data associated with them is destroyed.  You better not
663     * be using it when you do this.
664     * @param id Identifier of the Loader to be destroyed.
665     */
666    public void destroyLoader(int id) {
667        if (mCreatingLoader) {
668            throw new IllegalStateException("Called while creating a loader");
669        }
670
671        if (DEBUG) Log.v(TAG, "destroyLoader in " + this + " of " + id);
672        int idx = mLoaders.indexOfKey(id);
673        if (idx >= 0) {
674            LoaderInfo info = mLoaders.valueAt(idx);
675            mLoaders.removeAt(idx);
676            info.destroy();
677        }
678        idx = mInactiveLoaders.indexOfKey(id);
679        if (idx >= 0) {
680            LoaderInfo info = mInactiveLoaders.valueAt(idx);
681            mInactiveLoaders.removeAt(idx);
682            info.destroy();
683        }
684        if (mActivity != null && !hasRunningLoaders()) {
685            mActivity.mFragments.startPendingDeferredFragments();
686        }
687    }
688
689    /**
690     * Return the most recent Loader object associated with the
691     * given ID.
692     */
693    @SuppressWarnings("unchecked")
694    public <D> Loader<D> getLoader(int id) {
695        if (mCreatingLoader) {
696            throw new IllegalStateException("Called while creating a loader");
697        }
698
699        LoaderInfo loaderInfo = mLoaders.get(id);
700        if (loaderInfo != null) {
701            if (loaderInfo.mPendingLoader != null) {
702                return (Loader<D>)loaderInfo.mPendingLoader.mLoader;
703            }
704            return (Loader<D>)loaderInfo.mLoader;
705        }
706        return null;
707    }
708
709    void doStart() {
710        if (DEBUG) Log.v(TAG, "Starting in " + this);
711        if (mStarted) {
712            RuntimeException e = new RuntimeException("here");
713            e.fillInStackTrace();
714            Log.w(TAG, "Called doStart when already started: " + this, e);
715            return;
716        }
717
718        mStarted = true;
719
720        // Call out to sub classes so they can start their loaders
721        // Let the existing loaders know that we want to be notified when a load is complete
722        for (int i = mLoaders.size()-1; i >= 0; i--) {
723            mLoaders.valueAt(i).start();
724        }
725    }
726
727    void doStop() {
728        if (DEBUG) Log.v(TAG, "Stopping in " + this);
729        if (!mStarted) {
730            RuntimeException e = new RuntimeException("here");
731            e.fillInStackTrace();
732            Log.w(TAG, "Called doStop when not started: " + this, e);
733            return;
734        }
735
736        for (int i = mLoaders.size()-1; i >= 0; i--) {
737            mLoaders.valueAt(i).stop();
738        }
739        mStarted = false;
740    }
741
742    void doRetain() {
743        if (DEBUG) Log.v(TAG, "Retaining in " + this);
744        if (!mStarted) {
745            RuntimeException e = new RuntimeException("here");
746            e.fillInStackTrace();
747            Log.w(TAG, "Called doRetain when not started: " + this, e);
748            return;
749        }
750
751        mRetaining = true;
752        mStarted = false;
753        for (int i = mLoaders.size()-1; i >= 0; i--) {
754            mLoaders.valueAt(i).retain();
755        }
756    }
757
758    void finishRetain() {
759        if (mRetaining) {
760            if (DEBUG) Log.v(TAG, "Finished Retaining in " + this);
761
762            mRetaining = false;
763            for (int i = mLoaders.size()-1; i >= 0; i--) {
764                mLoaders.valueAt(i).finishRetain();
765            }
766        }
767    }
768
769    void doReportNextStart() {
770        for (int i = mLoaders.size()-1; i >= 0; i--) {
771            mLoaders.valueAt(i).mReportNextStart = true;
772        }
773    }
774
775    void doReportStart() {
776        for (int i = mLoaders.size()-1; i >= 0; i--) {
777            mLoaders.valueAt(i).reportStart();
778        }
779    }
780
781    void doDestroy() {
782        if (!mRetaining) {
783            if (DEBUG) Log.v(TAG, "Destroying Active in " + this);
784            for (int i = mLoaders.size()-1; i >= 0; i--) {
785                mLoaders.valueAt(i).destroy();
786            }
787        }
788
789        if (DEBUG) Log.v(TAG, "Destroying Inactive in " + this);
790        for (int i = mInactiveLoaders.size()-1; i >= 0; i--) {
791            mInactiveLoaders.valueAt(i).destroy();
792        }
793        mInactiveLoaders.clear();
794    }
795
796    @Override
797    public String toString() {
798        StringBuilder sb = new StringBuilder(128);
799        sb.append("LoaderManager{");
800        sb.append(Integer.toHexString(System.identityHashCode(this)));
801        sb.append(" in ");
802        DebugUtils.buildShortClassTag(mActivity, sb);
803        sb.append("}}");
804        return sb.toString();
805    }
806
807    @Override
808    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
809        if (mLoaders.size() > 0) {
810            writer.print(prefix); writer.println("Active Loaders:");
811            String innerPrefix = prefix + "    ";
812            for (int i=0; i < mLoaders.size(); i++) {
813                LoaderInfo li = mLoaders.valueAt(i);
814                writer.print(prefix); writer.print("  #"); writer.print(mLoaders.keyAt(i));
815                        writer.print(": "); writer.println(li.toString());
816                li.dump(innerPrefix, fd, writer, args);
817            }
818        }
819        if (mInactiveLoaders.size() > 0) {
820            writer.print(prefix); writer.println("Inactive Loaders:");
821            String innerPrefix = prefix + "    ";
822            for (int i=0; i < mInactiveLoaders.size(); i++) {
823                LoaderInfo li = mInactiveLoaders.valueAt(i);
824                writer.print(prefix); writer.print("  #"); writer.print(mInactiveLoaders.keyAt(i));
825                        writer.print(": "); writer.println(li.toString());
826                li.dump(innerPrefix, fd, writer, args);
827            }
828        }
829    }
830
831    public boolean hasRunningLoaders() {
832        boolean loadersRunning = false;
833        final int count = mLoaders.size();
834        for (int i = 0; i < count; i++) {
835            final LoaderInfo li = mLoaders.valueAt(i);
836            loadersRunning |= li.mStarted && !li.mDeliveredData;
837        }
838        return loadersRunning;
839    }
840}
841