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