Move to Android N-MR1 SDK.
[android_tools.git] / sdk / sources / android-25 / android / support / v4 / app / LoaderManager.java
blob72718ae0ab557eee1bb268da19884ecde1fcb94f
1 /*
2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package android.support.v4.app;
19 import android.app.Activity;
20 import android.os.Bundle;
21 import android.support.v4.content.Loader;
22 import android.support.v4.util.DebugUtils;
23 import android.support.v4.util.SparseArrayCompat;
24 import android.util.Log;
26 import java.io.FileDescriptor;
27 import java.io.PrintWriter;
28 import java.lang.reflect.Modifier;
30 /**
31 * Static library support version of the framework's {@link android.app.LoaderManager}.
32 * Used to write apps that run on platforms prior to Android 3.0. When running
33 * on Android 3.0 or above, this implementation is still used; it does not try
34 * to switch to the framework's implementation. See the framework SDK
35 * documentation for a class overview.
37 * <p>Your activity must derive from {@link FragmentActivity} to use this.
39 public abstract class LoaderManager {
40 /**
41 * Callback interface for a client to interact with the manager.
43 public interface LoaderCallbacks<D> {
44 /**
45 * Instantiate and return a new Loader for the given ID.
47 * @param id The ID whose loader is to be created.
48 * @param args Any arguments supplied by the caller.
49 * @return Return a new Loader instance that is ready to start loading.
51 public Loader<D> onCreateLoader(int id, Bundle args);
53 /**
54 * Called when a previously created loader has finished its load. Note
55 * that normally an application is <em>not</em> allowed to commit fragment
56 * transactions while in this call, since it can happen after an
57 * activity's state is saved. See {@link FragmentManager#beginTransaction()
58 * FragmentManager.openTransaction()} for further discussion on this.
60 * <p>This function is guaranteed to be called prior to the release of
61 * the last data that was supplied for this Loader. At this point
62 * you should remove all use of the old data (since it will be released
63 * soon), but should not do your own release of the data since its Loader
64 * owns it and will take care of that. The Loader will take care of
65 * management of its data so you don't have to. In particular:
67 * <ul>
68 * <li> <p>The Loader will monitor for changes to the data, and report
69 * them to you through new calls here. You should not monitor the
70 * data yourself. For example, if the data is a {@link android.database.Cursor}
71 * and you place it in a {@link android.widget.CursorAdapter}, use
72 * the {@link android.widget.CursorAdapter#CursorAdapter(android.content.Context,
73 * android.database.Cursor, int)} constructor <em>without</em> passing
74 * in either {@link android.widget.CursorAdapter#FLAG_AUTO_REQUERY}
75 * or {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER}
76 * (that is, use 0 for the flags argument). This prevents the CursorAdapter
77 * from doing its own observing of the Cursor, which is not needed since
78 * when a change happens you will get a new Cursor throw another call
79 * here.
80 * <li> The Loader will release the data once it knows the application
81 * is no longer using it. For example, if the data is
82 * a {@link android.database.Cursor} from a {@link android.content.CursorLoader},
83 * you should not call close() on it yourself. If the Cursor is being placed in a
84 * {@link android.widget.CursorAdapter}, you should use the
85 * {@link android.widget.CursorAdapter#swapCursor(android.database.Cursor)}
86 * method so that the old Cursor is not closed.
87 * </ul>
89 * @param loader The Loader that has finished.
90 * @param data The data generated by the Loader.
92 public void onLoadFinished(Loader<D> loader, D data);
94 /**
95 * Called when a previously created loader is being reset, and thus
96 * making its data unavailable. The application should at this point
97 * remove any references it has to the Loader's data.
99 * @param loader The Loader that is being reset.
101 public void onLoaderReset(Loader<D> loader);
105 * Ensures a loader is initialized and active. If the loader doesn't
106 * already exist, one is created and (if the activity/fragment is currently
107 * started) starts the loader. Otherwise the last created
108 * loader is re-used.
110 * <p>In either case, the given callback is associated with the loader, and
111 * will be called as the loader state changes. If at the point of call
112 * the caller is in its started state, and the requested loader
113 * already exists and has generated its data, then
114 * callback {@link LoaderCallbacks#onLoadFinished} will
115 * be called immediately (inside of this function), so you must be prepared
116 * for this to happen.
118 * @param id A unique identifier for this loader. Can be whatever you want.
119 * Identifiers are scoped to a particular LoaderManager instance.
120 * @param args Optional arguments to supply to the loader at construction.
121 * If a loader already exists (a new one does not need to be created), this
122 * parameter will be ignored and the last arguments continue to be used.
123 * @param callback Interface the LoaderManager will call to report about
124 * changes in the state of the loader. Required.
126 public abstract <D> Loader<D> initLoader(int id, Bundle args,
127 LoaderManager.LoaderCallbacks<D> callback);
130 * Starts a new or restarts an existing {@link android.content.Loader} in
131 * this manager, registers the callbacks to it,
132 * and (if the activity/fragment is currently started) starts loading it.
133 * If a loader with the same id has previously been
134 * started it will automatically be destroyed when the new loader completes
135 * its work. The callback will be delivered before the old loader
136 * is destroyed.
138 * @param id A unique identifier for this loader. Can be whatever you want.
139 * Identifiers are scoped to a particular LoaderManager instance.
140 * @param args Optional arguments to supply to the loader at construction.
141 * @param callback Interface the LoaderManager will call to report about
142 * changes in the state of the loader. Required.
144 public abstract <D> Loader<D> restartLoader(int id, Bundle args,
145 LoaderManager.LoaderCallbacks<D> callback);
148 * Stops and removes the loader with the given ID. If this loader
149 * had previously reported data to the client through
150 * {@link LoaderCallbacks#onLoadFinished(Loader, Object)}, a call
151 * will be made to {@link LoaderCallbacks#onLoaderReset(Loader)}.
153 public abstract void destroyLoader(int id);
156 * Return the Loader with the given id or null if no matching Loader
157 * is found.
159 public abstract <D> Loader<D> getLoader(int id);
162 * Print the LoaderManager's state into the given stream.
164 * @param prefix Text to print at the front of each line.
165 * @param fd The raw file descriptor that the dump is being sent to.
166 * @param writer A PrintWriter to which the dump is to be set.
167 * @param args Additional arguments to the dump request.
169 public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args);
172 * Control whether the framework's internal loader manager debugging
173 * logs are turned on. If enabled, you will see output in logcat as
174 * the framework performs loader operations.
176 public static void enableDebugLogging(boolean enabled) {
177 LoaderManagerImpl.DEBUG = enabled;
181 * Returns true if any loaders managed are currently running and have not
182 * returned data to the application yet.
184 public boolean hasRunningLoaders() { return false; }
187 class LoaderManagerImpl extends LoaderManager {
188 static final String TAG = "LoaderManager";
189 static boolean DEBUG = false;
191 // These are the currently active loaders. A loader is here
192 // from the time its load is started until it has been explicitly
193 // stopped or restarted by the application.
194 final SparseArrayCompat<LoaderInfo> mLoaders = new SparseArrayCompat<LoaderInfo>();
196 // These are previously run loaders. This list is maintained internally
197 // to avoid destroying a loader while an application is still using it.
198 // It allows an application to restart a loader, but continue using its
199 // previously run loader until the new loader's data is available.
200 final SparseArrayCompat<LoaderInfo> mInactiveLoaders = new SparseArrayCompat<LoaderInfo>();
202 final String mWho;
204 boolean mStarted;
205 boolean mRetaining;
206 boolean mRetainingStarted;
208 boolean mCreatingLoader;
209 FragmentHostCallback mHost;
211 final class LoaderInfo implements Loader.OnLoadCompleteListener<Object>,
212 Loader.OnLoadCanceledListener<Object> {
213 final int mId;
214 final Bundle mArgs;
215 LoaderManager.LoaderCallbacks<Object> mCallbacks;
216 Loader<Object> mLoader;
217 boolean mHaveData;
218 boolean mDeliveredData;
219 Object mData;
220 @SuppressWarnings("hiding")
221 boolean mStarted;
222 @SuppressWarnings("hiding")
223 boolean mRetaining;
224 @SuppressWarnings("hiding")
225 boolean mRetainingStarted;
226 boolean mReportNextStart;
227 boolean mDestroyed;
228 boolean mListenerRegistered;
230 LoaderInfo mPendingLoader;
232 public LoaderInfo(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callbacks) {
233 mId = id;
234 mArgs = args;
235 mCallbacks = callbacks;
238 void start() {
239 if (mRetaining && mRetainingStarted) {
240 // Our owner is started, but we were being retained from a
241 // previous instance in the started state... so there is really
242 // nothing to do here, since the loaders are still started.
243 mStarted = true;
244 return;
247 if (mStarted) {
248 // If loader already started, don't restart.
249 return;
252 mStarted = true;
254 if (DEBUG) Log.v(TAG, " Starting: " + this);
255 if (mLoader == null && mCallbacks != null) {
256 mLoader = mCallbacks.onCreateLoader(mId, mArgs);
258 if (mLoader != null) {
259 if (mLoader.getClass().isMemberClass()
260 && !Modifier.isStatic(mLoader.getClass().getModifiers())) {
261 throw new IllegalArgumentException(
262 "Object returned from onCreateLoader must not be a non-static inner member class: "
263 + mLoader);
265 if (!mListenerRegistered) {
266 mLoader.registerListener(mId, this);
267 mLoader.registerOnLoadCanceledListener(this);
268 mListenerRegistered = true;
270 mLoader.startLoading();
274 void retain() {
275 if (DEBUG) Log.v(TAG, " Retaining: " + this);
276 mRetaining = true;
277 mRetainingStarted = mStarted;
278 mStarted = false;
279 mCallbacks = null;
282 void finishRetain() {
283 if (mRetaining) {
284 if (DEBUG) Log.v(TAG, " Finished Retaining: " + this);
285 mRetaining = false;
286 if (mStarted != mRetainingStarted) {
287 if (!mStarted) {
288 // This loader was retained in a started state, but
289 // at the end of retaining everything our owner is
290 // no longer started... so make it stop.
291 stop();
296 if (mStarted && mHaveData && !mReportNextStart) {
297 // This loader has retained its data, either completely across
298 // a configuration change or just whatever the last data set
299 // was after being restarted from a stop, and now at the point of
300 // finishing the retain we find we remain started, have
301 // our data, and the owner has a new callback... so
302 // let's deliver the data now.
303 callOnLoadFinished(mLoader, mData);
307 void reportStart() {
308 if (mStarted) {
309 if (mReportNextStart) {
310 mReportNextStart = false;
311 if (mHaveData && !mRetaining) {
312 callOnLoadFinished(mLoader, mData);
318 void stop() {
319 if (DEBUG) Log.v(TAG, " Stopping: " + this);
320 mStarted = false;
321 if (!mRetaining) {
322 if (mLoader != null && mListenerRegistered) {
323 // Let the loader know we're done with it
324 mListenerRegistered = false;
325 mLoader.unregisterListener(this);
326 mLoader.unregisterOnLoadCanceledListener(this);
327 mLoader.stopLoading();
332 boolean cancel() {
333 if (DEBUG) Log.v(TAG, " Canceling: " + this);
334 if (mStarted && mLoader != null && mListenerRegistered) {
335 final boolean cancelLoadResult = mLoader.cancelLoad();
336 if (!cancelLoadResult) {
337 onLoadCanceled(mLoader);
339 return cancelLoadResult;
341 return false;
344 void destroy() {
345 if (DEBUG) Log.v(TAG, " Destroying: " + this);
346 mDestroyed = true;
347 boolean needReset = mDeliveredData;
348 mDeliveredData = false;
349 if (mCallbacks != null && mLoader != null && mHaveData && needReset) {
350 if (DEBUG) Log.v(TAG, " Resetting: " + this);
351 String lastBecause = null;
352 if (mHost != null) {
353 lastBecause = mHost.mFragmentManager.mNoTransactionsBecause;
354 mHost.mFragmentManager.mNoTransactionsBecause = "onLoaderReset";
356 try {
357 mCallbacks.onLoaderReset(mLoader);
358 } finally {
359 if (mHost != null) {
360 mHost.mFragmentManager.mNoTransactionsBecause = lastBecause;
364 mCallbacks = null;
365 mData = null;
366 mHaveData = false;
367 if (mLoader != null) {
368 if (mListenerRegistered) {
369 mListenerRegistered = false;
370 mLoader.unregisterListener(this);
371 mLoader.unregisterOnLoadCanceledListener(this);
373 mLoader.reset();
375 if (mPendingLoader != null) {
376 mPendingLoader.destroy();
380 @Override
381 public void onLoadCanceled(Loader<Object> loader) {
382 if (DEBUG) Log.v(TAG, "onLoadCanceled: " + this);
384 if (mDestroyed) {
385 if (DEBUG) Log.v(TAG, " Ignoring load canceled -- destroyed");
386 return;
389 if (mLoaders.get(mId) != this) {
390 // This cancellation message is not coming from the current active loader.
391 // We don't care about it.
392 if (DEBUG) Log.v(TAG, " Ignoring load canceled -- not active");
393 return;
396 LoaderInfo pending = mPendingLoader;
397 if (pending != null) {
398 // There is a new request pending and we were just
399 // waiting for the old one to cancel or complete before starting
400 // it. So now it is time, switch over to the new loader.
401 if (DEBUG) Log.v(TAG, " Switching to pending loader: " + pending);
402 mPendingLoader = null;
403 mLoaders.put(mId, null);
404 destroy();
405 installLoader(pending);
409 @Override
410 public void onLoadComplete(Loader<Object> loader, Object data) {
411 if (DEBUG) Log.v(TAG, "onLoadComplete: " + this);
413 if (mDestroyed) {
414 if (DEBUG) Log.v(TAG, " Ignoring load complete -- destroyed");
415 return;
418 if (mLoaders.get(mId) != this) {
419 // This data is not coming from the current active loader.
420 // We don't care about it.
421 if (DEBUG) Log.v(TAG, " Ignoring load complete -- not active");
422 return;
425 LoaderInfo pending = mPendingLoader;
426 if (pending != null) {
427 // There is a new request pending and we were just
428 // waiting for the old one to complete before starting
429 // it. So now it is time, switch over to the new loader.
430 if (DEBUG) Log.v(TAG, " Switching to pending loader: " + pending);
431 mPendingLoader = null;
432 mLoaders.put(mId, null);
433 destroy();
434 installLoader(pending);
435 return;
438 // Notify of the new data so the app can switch out the old data before
439 // we try to destroy it.
440 if (mData != data || !mHaveData) {
441 mData = data;
442 mHaveData = true;
443 if (mStarted) {
444 callOnLoadFinished(loader, data);
448 //if (DEBUG) Log.v(TAG, " onLoadFinished returned: " + this);
450 // We have now given the application the new loader with its
451 // loaded data, so it should have stopped using the previous
452 // loader. If there is a previous loader on the inactive list,
453 // clean it up.
454 LoaderInfo info = mInactiveLoaders.get(mId);
455 if (info != null && info != this) {
456 info.mDeliveredData = false;
457 info.destroy();
458 mInactiveLoaders.remove(mId);
461 if (mHost != null && !hasRunningLoaders()) {
462 mHost.mFragmentManager.startPendingDeferredFragments();
466 void callOnLoadFinished(Loader<Object> loader, Object data) {
467 if (mCallbacks != null) {
468 String lastBecause = null;
469 if (mHost != null) {
470 lastBecause = mHost.mFragmentManager.mNoTransactionsBecause;
471 mHost.mFragmentManager.mNoTransactionsBecause = "onLoadFinished";
473 try {
474 if (DEBUG) Log.v(TAG, " onLoadFinished in " + loader + ": "
475 + loader.dataToString(data));
476 mCallbacks.onLoadFinished(loader, data);
477 } finally {
478 if (mHost != null) {
479 mHost.mFragmentManager.mNoTransactionsBecause = lastBecause;
482 mDeliveredData = true;
486 @Override
487 public String toString() {
488 StringBuilder sb = new StringBuilder(64);
489 sb.append("LoaderInfo{");
490 sb.append(Integer.toHexString(System.identityHashCode(this)));
491 sb.append(" #");
492 sb.append(mId);
493 sb.append(" : ");
494 DebugUtils.buildShortClassTag(mLoader, sb);
495 sb.append("}}");
496 return sb.toString();
499 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
500 writer.print(prefix); writer.print("mId="); writer.print(mId);
501 writer.print(" mArgs="); writer.println(mArgs);
502 writer.print(prefix); writer.print("mCallbacks="); writer.println(mCallbacks);
503 writer.print(prefix); writer.print("mLoader="); writer.println(mLoader);
504 if (mLoader != null) {
505 mLoader.dump(prefix + " ", fd, writer, args);
507 if (mHaveData || mDeliveredData) {
508 writer.print(prefix); writer.print("mHaveData="); writer.print(mHaveData);
509 writer.print(" mDeliveredData="); writer.println(mDeliveredData);
510 writer.print(prefix); writer.print("mData="); writer.println(mData);
512 writer.print(prefix); writer.print("mStarted="); writer.print(mStarted);
513 writer.print(" mReportNextStart="); writer.print(mReportNextStart);
514 writer.print(" mDestroyed="); writer.println(mDestroyed);
515 writer.print(prefix); writer.print("mRetaining="); writer.print(mRetaining);
516 writer.print(" mRetainingStarted="); writer.print(mRetainingStarted);
517 writer.print(" mListenerRegistered="); writer.println(mListenerRegistered);
518 if (mPendingLoader != null) {
519 writer.print(prefix); writer.println("Pending Loader ");
520 writer.print(mPendingLoader); writer.println(":");
521 mPendingLoader.dump(prefix + " ", fd, writer, args);
526 LoaderManagerImpl(String who, FragmentHostCallback host, boolean started) {
527 mWho = who;
528 mHost = host;
529 mStarted = started;
532 void updateHostController(FragmentHostCallback host) {
533 mHost = host;
536 private LoaderInfo createLoader(int id, Bundle args,
537 LoaderManager.LoaderCallbacks<Object> callback) {
538 LoaderInfo info = new LoaderInfo(id, args, callback);
539 Loader<Object> loader = callback.onCreateLoader(id, args);
540 info.mLoader = loader;
541 return info;
544 private LoaderInfo createAndInstallLoader(int id, Bundle args,
545 LoaderManager.LoaderCallbacks<Object> callback) {
546 try {
547 mCreatingLoader = true;
548 LoaderInfo info = createLoader(id, args, callback);
549 installLoader(info);
550 return info;
551 } finally {
552 mCreatingLoader = false;
556 void installLoader(LoaderInfo info) {
557 mLoaders.put(info.mId, info);
558 if (mStarted) {
559 // The activity will start all existing loaders in it's onStart(),
560 // so only start them here if we're past that point of the activity's
561 // life cycle
562 info.start();
567 * Call to initialize a particular ID with a Loader. If this ID already
568 * has a Loader associated with it, it is left unchanged and any previous
569 * callbacks replaced with the newly provided ones. If there is not currently
570 * a Loader for the ID, a new one is created and started.
572 * <p>This function should generally be used when a component is initializing,
573 * to ensure that a Loader it relies on is created. This allows it to re-use
574 * an existing Loader's data if there already is one, so that for example
575 * when an {@link Activity} is re-created after a configuration change it
576 * does not need to re-create its loaders.
578 * <p>Note that in the case where an existing Loader is re-used, the
579 * <var>args</var> given here <em>will be ignored</em> because you will
580 * continue using the previous Loader.
582 * @param id A unique (to this LoaderManager instance) identifier under
583 * which to manage the new Loader.
584 * @param args Optional arguments that will be propagated to
585 * {@link android.support.v4.app.LoaderManager.LoaderCallbacks#onCreateLoader(int, Bundle) LoaderCallbacks.onCreateLoader()}.
586 * @param callback Interface implementing management of this Loader. Required.
587 * Its onCreateLoader() method will be called while inside of the function to
588 * instantiate the Loader object.
590 @Override
591 @SuppressWarnings("unchecked")
592 public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
593 if (mCreatingLoader) {
594 throw new IllegalStateException("Called while creating a loader");
597 LoaderInfo info = mLoaders.get(id);
599 if (DEBUG) Log.v(TAG, "initLoader in " + this + ": args=" + args);
601 if (info == null) {
602 // Loader doesn't already exist; create.
603 info = createAndInstallLoader(id, args, (LoaderManager.LoaderCallbacks<Object>)callback);
604 if (DEBUG) Log.v(TAG, " Created new loader " + info);
605 } else {
606 if (DEBUG) Log.v(TAG, " Re-using existing loader " + info);
607 info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
610 if (info.mHaveData && mStarted) {
611 // If the loader has already generated its data, report it now.
612 info.callOnLoadFinished(info.mLoader, info.mData);
615 return (Loader<D>)info.mLoader;
619 * Call to re-create the Loader associated with a particular ID. If there
620 * is currently a Loader associated with this ID, it will be
621 * canceled/stopped/destroyed as appropriate. A new Loader with the given
622 * arguments will be created and its data delivered to you once available.
624 * <p>This function does some throttling of Loaders. If too many Loaders
625 * have been created for the given ID but not yet generated their data,
626 * new calls to this function will create and return a new Loader but not
627 * actually start it until some previous loaders have completed.
629 * <p>After calling this function, any previous Loaders associated with
630 * this ID will be considered invalid, and you will receive no further
631 * data updates from them.
633 * @param id A unique (to this LoaderManager instance) identifier under
634 * which to manage the new Loader.
635 * @param args Optional arguments that will be propagated to
636 * {@link android.support.v4.app.LoaderManager.LoaderCallbacks#onCreateLoader(int, Bundle) LoaderCallbacks.onCreateLoader()}.
637 * @param callback Interface implementing management of this Loader. Required.
638 * Its onCreateLoader() method will be called while inside of the function to
639 * instantiate the Loader object.
641 @Override
642 @SuppressWarnings("unchecked")
643 public <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
644 if (mCreatingLoader) {
645 throw new IllegalStateException("Called while creating a loader");
648 LoaderInfo info = mLoaders.get(id);
649 if (DEBUG) Log.v(TAG, "restartLoader in " + this + ": args=" + args);
650 if (info != null) {
651 LoaderInfo inactive = mInactiveLoaders.get(id);
652 if (inactive != null) {
653 if (info.mHaveData) {
654 // This loader now has data... we are probably being
655 // called from within onLoadComplete, where we haven't
656 // yet destroyed the last inactive loader. So just do
657 // that now.
658 if (DEBUG) Log.v(TAG, " Removing last inactive loader: " + info);
659 inactive.mDeliveredData = false;
660 inactive.destroy();
661 info.mLoader.abandon();
662 mInactiveLoaders.put(id, info);
663 } else {
664 // We already have an inactive loader for this ID that we are
665 // waiting for! Try to cancel; if this returns true then the task is still
666 // running and we have more work to do.
667 if (!info.cancel()) {
668 // The current Loader has not been started or was successfully canceled,
669 // we thus have no reason to keep it around. Remove it and a new
670 // LoaderInfo will be created below.
671 if (DEBUG) Log.v(TAG, " Current loader is stopped; replacing");
672 mLoaders.put(id, null);
673 info.destroy();
674 } else {
675 // Now we have three active loaders... we'll queue
676 // up this request to be processed once one of the other loaders
677 // finishes.
678 if (DEBUG) Log.v(TAG,
679 " Current loader is running; configuring pending loader");
680 if (info.mPendingLoader != null) {
681 if (DEBUG) Log.v(TAG, " Removing pending loader: " + info.mPendingLoader);
682 info.mPendingLoader.destroy();
683 info.mPendingLoader = null;
685 if (DEBUG) Log.v(TAG, " Enqueuing as new pending loader");
686 info.mPendingLoader = createLoader(id, args,
687 (LoaderManager.LoaderCallbacks<Object>)callback);
688 return (Loader<D>)info.mPendingLoader.mLoader;
691 } else {
692 // Keep track of the previous instance of this loader so we can destroy
693 // it when the new one completes.
694 if (DEBUG) Log.v(TAG, " Making last loader inactive: " + info);
695 info.mLoader.abandon();
696 mInactiveLoaders.put(id, info);
700 info = createAndInstallLoader(id, args, (LoaderManager.LoaderCallbacks<Object>)callback);
701 return (Loader<D>)info.mLoader;
705 * Rip down, tear apart, shred to pieces a current Loader ID. After returning
706 * from this function, any Loader objects associated with this ID are
707 * destroyed. Any data associated with them is destroyed. You better not
708 * be using it when you do this.
709 * @param id Identifier of the Loader to be destroyed.
711 @Override
712 public void destroyLoader(int id) {
713 if (mCreatingLoader) {
714 throw new IllegalStateException("Called while creating a loader");
717 if (DEBUG) Log.v(TAG, "destroyLoader in " + this + " of " + id);
718 int idx = mLoaders.indexOfKey(id);
719 if (idx >= 0) {
720 LoaderInfo info = mLoaders.valueAt(idx);
721 mLoaders.removeAt(idx);
722 info.destroy();
724 idx = mInactiveLoaders.indexOfKey(id);
725 if (idx >= 0) {
726 LoaderInfo info = mInactiveLoaders.valueAt(idx);
727 mInactiveLoaders.removeAt(idx);
728 info.destroy();
730 if (mHost != null && !hasRunningLoaders()) {
731 mHost.mFragmentManager.startPendingDeferredFragments();
736 * Return the most recent Loader object associated with the
737 * given ID.
739 @Override
740 @SuppressWarnings("unchecked")
741 public <D> Loader<D> getLoader(int id) {
742 if (mCreatingLoader) {
743 throw new IllegalStateException("Called while creating a loader");
746 LoaderInfo loaderInfo = mLoaders.get(id);
747 if (loaderInfo != null) {
748 if (loaderInfo.mPendingLoader != null) {
749 return (Loader<D>)loaderInfo.mPendingLoader.mLoader;
751 return (Loader<D>)loaderInfo.mLoader;
753 return null;
756 void doStart() {
757 if (DEBUG) Log.v(TAG, "Starting in " + this);
758 if (mStarted) {
759 RuntimeException e = new RuntimeException("here");
760 e.fillInStackTrace();
761 Log.w(TAG, "Called doStart when already started: " + this, e);
762 return;
765 mStarted = true;
767 // Call out to sub classes so they can start their loaders
768 // Let the existing loaders know that we want to be notified when a load is complete
769 for (int i = mLoaders.size()-1; i >= 0; i--) {
770 mLoaders.valueAt(i).start();
774 void doStop() {
775 if (DEBUG) Log.v(TAG, "Stopping in " + this);
776 if (!mStarted) {
777 RuntimeException e = new RuntimeException("here");
778 e.fillInStackTrace();
779 Log.w(TAG, "Called doStop when not started: " + this, e);
780 return;
783 for (int i = mLoaders.size()-1; i >= 0; i--) {
784 mLoaders.valueAt(i).stop();
786 mStarted = false;
789 void doRetain() {
790 if (DEBUG) Log.v(TAG, "Retaining in " + this);
791 if (!mStarted) {
792 RuntimeException e = new RuntimeException("here");
793 e.fillInStackTrace();
794 Log.w(TAG, "Called doRetain when not started: " + this, e);
795 return;
798 mRetaining = true;
799 mStarted = false;
800 for (int i = mLoaders.size()-1; i >= 0; i--) {
801 mLoaders.valueAt(i).retain();
805 void finishRetain() {
806 if (mRetaining) {
807 if (DEBUG) Log.v(TAG, "Finished Retaining in " + this);
809 mRetaining = false;
810 for (int i = mLoaders.size()-1; i >= 0; i--) {
811 mLoaders.valueAt(i).finishRetain();
816 void doReportNextStart() {
817 for (int i = mLoaders.size()-1; i >= 0; i--) {
818 mLoaders.valueAt(i).mReportNextStart = true;
822 void doReportStart() {
823 for (int i = mLoaders.size()-1; i >= 0; i--) {
824 mLoaders.valueAt(i).reportStart();
828 void doDestroy() {
829 if (!mRetaining) {
830 if (DEBUG) Log.v(TAG, "Destroying Active in " + this);
831 for (int i = mLoaders.size()-1; i >= 0; i--) {
832 mLoaders.valueAt(i).destroy();
834 mLoaders.clear();
837 if (DEBUG) Log.v(TAG, "Destroying Inactive in " + this);
838 for (int i = mInactiveLoaders.size()-1; i >= 0; i--) {
839 mInactiveLoaders.valueAt(i).destroy();
841 mInactiveLoaders.clear();
844 @Override
845 public String toString() {
846 StringBuilder sb = new StringBuilder(128);
847 sb.append("LoaderManager{");
848 sb.append(Integer.toHexString(System.identityHashCode(this)));
849 sb.append(" in ");
850 DebugUtils.buildShortClassTag(mHost, sb);
851 sb.append("}}");
852 return sb.toString();
855 @Override
856 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
857 if (mLoaders.size() > 0) {
858 writer.print(prefix); writer.println("Active Loaders:");
859 String innerPrefix = prefix + " ";
860 for (int i=0; i < mLoaders.size(); i++) {
861 LoaderInfo li = mLoaders.valueAt(i);
862 writer.print(prefix); writer.print(" #"); writer.print(mLoaders.keyAt(i));
863 writer.print(": "); writer.println(li.toString());
864 li.dump(innerPrefix, fd, writer, args);
867 if (mInactiveLoaders.size() > 0) {
868 writer.print(prefix); writer.println("Inactive Loaders:");
869 String innerPrefix = prefix + " ";
870 for (int i=0; i < mInactiveLoaders.size(); i++) {
871 LoaderInfo li = mInactiveLoaders.valueAt(i);
872 writer.print(prefix); writer.print(" #"); writer.print(mInactiveLoaders.keyAt(i));
873 writer.print(": "); writer.println(li.toString());
874 li.dump(innerPrefix, fd, writer, args);
879 @Override
880 public boolean hasRunningLoaders() {
881 boolean loadersRunning = false;
882 final int count = mLoaders.size();
883 for (int i = 0; i < count; i++) {
884 final LoaderInfo li = mLoaders.valueAt(i);
885 loadersRunning |= li.mStarted && !li.mDeliveredData;
887 return loadersRunning;