blob: 164141cff7a00fb6731d70e28229971c38491e9f [file] [log] [blame]
Dianne Hackbornc8017682010-07-06 13:34:38 -07001/*
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;
Dianne Hackbornc8017682010-07-06 13:34:38 -070020import android.os.Bundle;
Dianne Hackborna2ea7472010-12-20 12:10:01 -080021import android.util.DebugUtils;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -070022import android.util.Log;
Dianne Hackbornc8017682010-07-06 13:34:38 -070023import android.util.SparseArray;
24
Dianne Hackborn30d71892010-12-11 10:37:55 -080025import java.io.FileDescriptor;
26import java.io.PrintWriter;
Dianne Hackborn0e3b8f422010-12-20 23:22:11 -080027import java.lang.reflect.Modifier;
Dianne Hackborn30d71892010-12-11 10:37:55 -080028
Dianne Hackbornc8017682010-07-06 13:34:38 -070029/**
Dianne Hackborn4911b782010-07-15 12:54:39 -070030 * Interface associated with an {@link Activity} or {@link Fragment} for managing
Dianne Hackbornc9189352010-12-15 14:57:25 -080031 * 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 *
Dianne Hackborn9567a662011-04-19 18:44:03 -070037 * 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 *
Dianne Hackbornc9189352010-12-15 14:57:25 -080043 * <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 *
Dianne Hackborn9567a662011-04-19 18:44:03 -070048 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LoaderCursor.java
Dianne Hackbornc9189352010-12-15 14:57:25 -080049 * fragment_cursor}
Dianne Hackbornc8017682010-07-06 13:34:38 -070050 */
Dianne Hackbornab36acb2010-11-05 14:12:11 -070051public abstract class LoaderManager {
Dianne Hackborn4911b782010-07-15 12:54:39 -070052 /**
53 * Callback interface for a client to interact with the manager.
54 */
55 public interface LoaderCallbacks<D> {
56 /**
57 * Instantiate and return a new Loader for the given ID.
58 *
59 * @param id The ID whose loader is to be created.
60 * @param args Any arguments supplied by the caller.
61 * @return Return a new Loader instance that is ready to start loading.
62 */
63 public Loader<D> onCreateLoader(int id, Bundle args);
64
65 /**
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -070066 * Called when a previously created loader has finished its load. Note
67 * that normally an application is <em>not</em> allowed to commit fragment
68 * transactions while in this call, since it can happen after an
Dianne Hackborn48e7b452011-01-17 12:28:35 -080069 * activity's state is saved. See {@link FragmentManager#beginTransaction()
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -070070 * FragmentManager.openTransaction()} for further discussion on this.
71 *
Dianne Hackbornc9189352010-12-15 14:57:25 -080072 * <p>This function is guaranteed to be called prior to the release of
73 * the last data that was supplied for this Loader. At this point
74 * you should remove all use of the old data (since it will be released
75 * soon), but should not do your own release of the data since its Loader
76 * owns it and will take care of that. The Loader will take care of
77 * management of its data so you don't have to. In particular:
78 *
79 * <ul>
80 * <li> <p>The Loader will monitor for changes to the data, and report
81 * them to you through new calls here. You should not monitor the
82 * data yourself. For example, if the data is a {@link android.database.Cursor}
83 * and you place it in a {@link android.widget.CursorAdapter}, use
84 * the {@link android.widget.CursorAdapter#CursorAdapter(android.content.Context,
85 * android.database.Cursor, int)} constructor <em>without</em> passing
86 * in either {@link android.widget.CursorAdapter#FLAG_AUTO_REQUERY}
87 * or {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER}
88 * (that is, use 0 for the flags argument). This prevents the CursorAdapter
89 * from doing its own observing of the Cursor, which is not needed since
90 * when a change happens you will get a new Cursor throw another call
91 * here.
92 * <li> The Loader will release the data once it knows the application
93 * is no longer using it. For example, if the data is
94 * a {@link android.database.Cursor} from a {@link android.content.CursorLoader},
95 * you should not call close() on it yourself. If the Cursor is being placed in a
96 * {@link android.widget.CursorAdapter}, you should use the
97 * {@link android.widget.CursorAdapter#swapCursor(android.database.Cursor)}
98 * method so that the old Cursor is not closed.
99 * </ul>
100 *
Dianne Hackborn4911b782010-07-15 12:54:39 -0700101 * @param loader The Loader that has finished.
102 * @param data The data generated by the Loader.
103 */
104 public void onLoadFinished(Loader<D> loader, D data);
Dianne Hackbornc9189352010-12-15 14:57:25 -0800105
106 /**
107 * Called when a previously created loader is being reset, and thus
108 * making its data unavailable. The application should at this point
109 * remove any references it has to the Loader's data.
110 *
111 * @param loader The Loader that is being reset.
112 */
113 public void onLoaderReset(Loader<D> loader);
Dianne Hackborn4911b782010-07-15 12:54:39 -0700114 }
115
116 /**
117 * Ensures a loader is initialized and active. If the loader doesn't
118 * already exist, one is created and (if the activity/fragment is currently
119 * started) starts the loader. Otherwise the last created
120 * loader is re-used.
121 *
122 * <p>In either case, the given callback is associated with the loader, and
123 * will be called as the loader state changes. If at the point of call
124 * the caller is in its started state, and the requested loader
125 * already exists and has generated its data, then
Dianne Hackbornc9189352010-12-15 14:57:25 -0800126 * callback {@link LoaderCallbacks#onLoadFinished} will
Dianne Hackborn4911b782010-07-15 12:54:39 -0700127 * be called immediately (inside of this function), so you must be prepared
128 * for this to happen.
Dianne Hackbornc9189352010-12-15 14:57:25 -0800129 *
130 * @param id A unique identifier for this loader. Can be whatever you want.
131 * Identifiers are scoped to a particular LoaderManager instance.
132 * @param args Optional arguments to supply to the loader at construction.
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800133 * If a loader already exists (a new one does not need to be created), this
134 * parameter will be ignored and the last arguments continue to be used.
Dianne Hackbornc9189352010-12-15 14:57:25 -0800135 * @param callback Interface the LoaderManager will call to report about
136 * changes in the state of the loader. Required.
Dianne Hackborn4911b782010-07-15 12:54:39 -0700137 */
Dianne Hackbornab36acb2010-11-05 14:12:11 -0700138 public abstract <D> Loader<D> initLoader(int id, Bundle args,
Dianne Hackborn4911b782010-07-15 12:54:39 -0700139 LoaderManager.LoaderCallbacks<D> callback);
140
141 /**
Dianne Hackbornc9189352010-12-15 14:57:25 -0800142 * Starts a new or restarts an existing {@link android.content.Loader} in
143 * this manager, registers the callbacks to it,
Dianne Hackborn4911b782010-07-15 12:54:39 -0700144 * and (if the activity/fragment is currently started) starts loading it.
145 * If a loader with the same id has previously been
146 * started it will automatically be destroyed when the new loader completes
147 * its work. The callback will be delivered before the old loader
148 * is destroyed.
Dianne Hackbornc9189352010-12-15 14:57:25 -0800149 *
150 * @param id A unique identifier for this loader. Can be whatever you want.
151 * Identifiers are scoped to a particular LoaderManager instance.
152 * @param args Optional arguments to supply to the loader at construction.
153 * @param callback Interface the LoaderManager will call to report about
154 * changes in the state of the loader. Required.
Dianne Hackborn4911b782010-07-15 12:54:39 -0700155 */
Dianne Hackbornab36acb2010-11-05 14:12:11 -0700156 public abstract <D> Loader<D> restartLoader(int id, Bundle args,
Dianne Hackborn4911b782010-07-15 12:54:39 -0700157 LoaderManager.LoaderCallbacks<D> callback);
158
159 /**
Dianne Hackbornf73c75c2010-12-17 16:54:05 -0800160 * Stops and removes the loader with the given ID. If this loader
161 * had previously reported data to the client through
162 * {@link LoaderCallbacks#onLoadFinished(Loader, Object)}, a call
163 * will be made to {@link LoaderCallbacks#onLoaderReset(Loader)}.
Dianne Hackborn4911b782010-07-15 12:54:39 -0700164 */
Dianne Hackbornc9189352010-12-15 14:57:25 -0800165 public abstract void destroyLoader(int id);
166
167 /**
Dianne Hackborn4911b782010-07-15 12:54:39 -0700168 * Return the Loader with the given id or null if no matching Loader
169 * is found.
170 */
Dianne Hackbornab36acb2010-11-05 14:12:11 -0700171 public abstract <D> Loader<D> getLoader(int id);
Dianne Hackborn30d71892010-12-11 10:37:55 -0800172
173 /**
174 * Print the LoaderManager's state into the given stream.
175 *
176 * @param prefix Text to print at the front of each line.
177 * @param fd The raw file descriptor that the dump is being sent to.
178 * @param writer A PrintWriter to which the dump is to be set.
179 * @param args Additional arguments to the dump request.
180 */
181 public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args);
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800182
183 /**
184 * Control whether the framework's internal loader manager debugging
185 * logs are turned on. If enabled, you will see output in logcat as
186 * the framework performs loader operations.
187 */
188 public static void enableDebugLogging(boolean enabled) {
189 LoaderManagerImpl.DEBUG = enabled;
190 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700191}
192
Dianne Hackbornab36acb2010-11-05 14:12:11 -0700193class LoaderManagerImpl extends LoaderManager {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800194 static final String TAG = "LoaderManager";
Dianne Hackbornec541e12011-01-21 16:44:04 -0800195 static boolean DEBUG = false;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700196
197 // These are the currently active loaders. A loader is here
198 // from the time its load is started until it has been explicitly
199 // stopped or restarted by the application.
Dianne Hackborn2707d602010-07-09 18:01:20 -0700200 final SparseArray<LoaderInfo> mLoaders = new SparseArray<LoaderInfo>();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700201
202 // These are previously run loaders. This list is maintained internally
203 // to avoid destroying a loader while an application is still using it.
204 // It allows an application to restart a loader, but continue using its
205 // previously run loader until the new loader's data is available.
Dianne Hackborn2707d602010-07-09 18:01:20 -0700206 final SparseArray<LoaderInfo> mInactiveLoaders = new SparseArray<LoaderInfo>();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700207
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700208 Activity mActivity;
Dianne Hackborn2707d602010-07-09 18:01:20 -0700209 boolean mStarted;
210 boolean mRetaining;
211 boolean mRetainingStarted;
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800212
213 boolean mCreatingLoader;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700214
Dianne Hackbornc8017682010-07-06 13:34:38 -0700215 final class LoaderInfo implements Loader.OnLoadCompleteListener<Object> {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700216 final int mId;
217 final Bundle mArgs;
218 LoaderManager.LoaderCallbacks<Object> mCallbacks;
219 Loader<Object> mLoader;
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800220 boolean mHaveData;
221 boolean mDeliveredData;
Dianne Hackborn2707d602010-07-09 18:01:20 -0700222 Object mData;
223 boolean mStarted;
224 boolean mRetaining;
225 boolean mRetainingStarted;
226 boolean mDestroyed;
227 boolean mListenerRegistered;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800228
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800229 LoaderInfo mPendingLoader;
230
Dianne Hackborn2707d602010-07-09 18:01:20 -0700231 public LoaderInfo(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callbacks) {
232 mId = id;
233 mArgs = args;
234 mCallbacks = callbacks;
235 }
236
237 void start() {
238 if (mRetaining && mRetainingStarted) {
239 // Our owner is started, but we were being retained from a
240 // previous instance in the started state... so there is really
241 // nothing to do here, since the loaders are still started.
242 mStarted = true;
243 return;
244 }
245
Dianne Hackborn4911b782010-07-15 12:54:39 -0700246 if (mStarted) {
247 // If loader already started, don't restart.
248 return;
249 }
250
Dianne Hackborn0e3b8f422010-12-20 23:22:11 -0800251 mStarted = true;
252
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700253 if (DEBUG) Log.v(TAG, " Starting: " + this);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700254 if (mLoader == null && mCallbacks != null) {
255 mLoader = mCallbacks.onCreateLoader(mId, mArgs);
256 }
257 if (mLoader != null) {
Dianne Hackborn0e3b8f422010-12-20 23:22:11 -0800258 if (mLoader.getClass().isMemberClass()
259 && !Modifier.isStatic(mLoader.getClass().getModifiers())) {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800260 throw new IllegalArgumentException(
Dianne Hackborn0e3b8f422010-12-20 23:22:11 -0800261 "Object returned from onCreateLoader must not be a non-static inner member class: "
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800262 + mLoader);
263 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700264 if (!mListenerRegistered) {
265 mLoader.registerListener(mId, this);
266 mListenerRegistered = true;
267 }
Dianne Hackborn2707d602010-07-09 18:01:20 -0700268 mLoader.startLoading();
Dianne Hackborn2707d602010-07-09 18:01:20 -0700269 }
270 }
271
272 void retain() {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700273 if (DEBUG) Log.v(TAG, " Retaining: " + this);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700274 mRetaining = true;
275 mRetainingStarted = mStarted;
276 mStarted = false;
277 mCallbacks = null;
278 }
279
280 void finishRetain() {
281 if (mRetaining) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700282 if (DEBUG) Log.v(TAG, " Finished Retaining: " + this);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700283 mRetaining = false;
284 if (mStarted != mRetainingStarted) {
285 if (!mStarted) {
286 // This loader was retained in a started state, but
287 // at the end of retaining everything our owner is
288 // no longer started... so make it stop.
289 stop();
290 }
291 }
Dianne Hackbornc9189352010-12-15 14:57:25 -0800292 }
293
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800294 if (mStarted && mHaveData) {
Dianne Hackbornc9189352010-12-15 14:57:25 -0800295 // This loader has retained its data, either completely across
296 // a configuration change or just whatever the last data set
297 // was after being restarted from a stop, and now at the point of
298 // finishing the retain we find we remain started, have
299 // our data, and the owner has a new callback... so
300 // let's deliver the data now.
301 callOnLoadFinished(mLoader, mData);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700302 }
303 }
304
305 void stop() {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700306 if (DEBUG) Log.v(TAG, " Stopping: " + this);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700307 mStarted = false;
Dianne Hackborndebb2e22010-08-09 16:32:52 -0700308 if (!mRetaining) {
309 if (mLoader != null && mListenerRegistered) {
310 // Let the loader know we're done with it
311 mListenerRegistered = false;
312 mLoader.unregisterListener(this);
313 mLoader.stopLoading();
314 }
Dianne Hackborn2707d602010-07-09 18:01:20 -0700315 }
316 }
317
318 void destroy() {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700319 if (DEBUG) Log.v(TAG, " Destroying: " + this);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700320 mDestroyed = true;
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800321 boolean needReset = mDeliveredData;
322 mDeliveredData = false;
323 if (mCallbacks != null && mLoader != null && mHaveData && needReset) {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800324 if (DEBUG) Log.v(TAG, " Reseting: " + this);
Dianne Hackbornc9189352010-12-15 14:57:25 -0800325 String lastBecause = null;
326 if (mActivity != null) {
327 lastBecause = mActivity.mFragments.mNoTransactionsBecause;
328 mActivity.mFragments.mNoTransactionsBecause = "onLoaderReset";
329 }
330 try {
331 mCallbacks.onLoaderReset(mLoader);
332 } finally {
333 if (mActivity != null) {
334 mActivity.mFragments.mNoTransactionsBecause = lastBecause;
335 }
336 }
337 }
Dianne Hackborn2707d602010-07-09 18:01:20 -0700338 mCallbacks = null;
Dianne Hackbornc9189352010-12-15 14:57:25 -0800339 mData = null;
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800340 mHaveData = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -0700341 if (mLoader != null) {
342 if (mListenerRegistered) {
343 mListenerRegistered = false;
344 mLoader.unregisterListener(this);
345 }
Dianne Hackbornc9189352010-12-15 14:57:25 -0800346 mLoader.reset();
Dianne Hackborn2707d602010-07-09 18:01:20 -0700347 }
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800348 if (mPendingLoader != null) {
349 mPendingLoader.destroy();
350 }
Dianne Hackborn2707d602010-07-09 18:01:20 -0700351 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700352
353 @Override public void onLoadComplete(Loader<Object> loader, Object data) {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800354 if (DEBUG) Log.v(TAG, "onLoadComplete: " + this);
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800355
Dianne Hackborn2707d602010-07-09 18:01:20 -0700356 if (mDestroyed) {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800357 if (DEBUG) Log.v(TAG, " Ignoring load complete -- destroyed");
Dianne Hackborn2707d602010-07-09 18:01:20 -0700358 return;
359 }
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800360
361 if (mLoaders.get(mId) != this) {
362 // This data is not coming from the current active loader.
363 // We don't care about it.
364 if (DEBUG) Log.v(TAG, " Ignoring load complete -- not active");
365 return;
366 }
367
368 LoaderInfo pending = mPendingLoader;
369 if (pending != null) {
370 // There is a new request pending and we were just
371 // waiting for the old one to complete before starting
372 // it. So now it is time, switch over to the new loader.
373 if (DEBUG) Log.v(TAG, " Switching to pending loader: " + pending);
374 mPendingLoader = null;
375 mLoaders.put(mId, null);
376 destroy();
377 installLoader(pending);
378 return;
379 }
Dianne Hackborn2707d602010-07-09 18:01:20 -0700380
Dianne Hackbornc8017682010-07-06 13:34:38 -0700381 // Notify of the new data so the app can switch out the old data before
382 // we try to destroy it.
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800383 if (mData != data || !mHaveData) {
Dianne Hackborn0e3b8f422010-12-20 23:22:11 -0800384 mData = data;
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800385 mHaveData = true;
Dianne Hackborn0e3b8f422010-12-20 23:22:11 -0800386 if (mStarted) {
387 callOnLoadFinished(loader, data);
388 }
Dianne Hackbornc9189352010-12-15 14:57:25 -0800389 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700390
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800391 //if (DEBUG) Log.v(TAG, " onLoadFinished returned: " + this);
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700392
393 // We have now given the application the new loader with its
394 // loaded data, so it should have stopped using the previous
395 // loader. If there is a previous loader on the inactive list,
396 // clean it up.
Dianne Hackborn2707d602010-07-09 18:01:20 -0700397 LoaderInfo info = mInactiveLoaders.get(mId);
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700398 if (info != null && info != this) {
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800399 info.mDeliveredData = false;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700400 info.destroy();
Dianne Hackborn2707d602010-07-09 18:01:20 -0700401 mInactiveLoaders.remove(mId);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700402 }
403 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700404
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700405 void callOnLoadFinished(Loader<Object> loader, Object data) {
406 if (mCallbacks != null) {
407 String lastBecause = null;
408 if (mActivity != null) {
409 lastBecause = mActivity.mFragments.mNoTransactionsBecause;
410 mActivity.mFragments.mNoTransactionsBecause = "onLoadFinished";
411 }
412 try {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800413 if (DEBUG) Log.v(TAG, " onLoadFinished in " + loader + ": "
414 + loader.dataToString(data));
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700415 mCallbacks.onLoadFinished(loader, data);
416 } finally {
417 if (mActivity != null) {
418 mActivity.mFragments.mNoTransactionsBecause = lastBecause;
419 }
420 }
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800421 mDeliveredData = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700422 }
423 }
424
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700425 @Override
426 public String toString() {
427 StringBuilder sb = new StringBuilder(64);
428 sb.append("LoaderInfo{");
429 sb.append(Integer.toHexString(System.identityHashCode(this)));
430 sb.append(" #");
431 sb.append(mId);
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800432 sb.append(" : ");
433 DebugUtils.buildShortClassTag(mLoader, sb);
434 sb.append("}}");
Dianne Hackborn30d71892010-12-11 10:37:55 -0800435 return sb.toString();
436 }
437
438 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
439 writer.print(prefix); writer.print("mId="); writer.print(mId);
440 writer.print(" mArgs="); writer.println(mArgs);
441 writer.print(prefix); writer.print("mCallbacks="); writer.println(mCallbacks);
442 writer.print(prefix); writer.print("mLoader="); writer.println(mLoader);
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800443 if (mLoader != null) {
444 mLoader.dump(prefix + " ", fd, writer, args);
445 }
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800446 if (mHaveData || mDeliveredData) {
447 writer.print(prefix); writer.print("mHaveData="); writer.print(mHaveData);
448 writer.print(" mDeliveredData="); writer.println(mDeliveredData);
449 writer.print(prefix); writer.print("mData="); writer.println(mData);
450 }
Dianne Hackborn30d71892010-12-11 10:37:55 -0800451 writer.print(prefix); writer.print("mStarted="); writer.print(mStarted);
452 writer.print(" mRetaining="); writer.print(mRetaining);
Dianne Hackbornf73c75c2010-12-17 16:54:05 -0800453 writer.print(" mDestroyed="); writer.println(mDestroyed);
Dianne Hackborn0e3b8f422010-12-20 23:22:11 -0800454 writer.print(prefix); writer.print("mListenerRegistered=");
455 writer.println(mListenerRegistered);
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800456 if (mPendingLoader != null) {
457 writer.print(prefix); writer.println("Pending Loader ");
458 writer.print(mPendingLoader); writer.println(":");
459 mPendingLoader.dump(prefix + " ", fd, writer, args);
460 }
Dianne Hackborn30d71892010-12-11 10:37:55 -0800461 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700462 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700463
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700464 LoaderManagerImpl(Activity activity, boolean started) {
465 mActivity = activity;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700466 mStarted = started;
467 }
468
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700469 void updateActivity(Activity activity) {
470 mActivity = activity;
471 }
472
Dianne Hackborn2707d602010-07-09 18:01:20 -0700473 private LoaderInfo createLoader(int id, Bundle args,
474 LoaderManager.LoaderCallbacks<Object> callback) {
475 LoaderInfo info = new LoaderInfo(id, args, (LoaderManager.LoaderCallbacks<Object>)callback);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700476 Loader<Object> loader = callback.onCreateLoader(id, args);
477 info.mLoader = (Loader<Object>)loader;
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800478 return info;
479 }
480
481 private LoaderInfo createAndInstallLoader(int id, Bundle args,
482 LoaderManager.LoaderCallbacks<Object> callback) {
483 try {
484 mCreatingLoader = true;
485 LoaderInfo info = createLoader(id, args, callback);
486 installLoader(info);
487 return info;
488 } finally {
489 mCreatingLoader = false;
490 }
491 }
492
493 void installLoader(LoaderInfo info) {
494 mLoaders.put(info.mId, info);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700495 if (mStarted) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700496 // The activity will start all existing loaders in it's onStart(),
497 // so only start them here if we're past that point of the activitiy's
498 // life cycle
499 info.start();
Dianne Hackborn2707d602010-07-09 18:01:20 -0700500 }
Dianne Hackborn2707d602010-07-09 18:01:20 -0700501 }
502
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800503 /**
504 * Call to initialize a particular ID with a Loader. If this ID already
505 * has a Loader associated with it, it is left unchanged and any previous
506 * callbacks replaced with the newly provided ones. If there is not currently
507 * a Loader for the ID, a new one is created and started.
508 *
509 * <p>This function should generally be used when a component is initializing,
510 * to ensure that a Loader it relies on is created. This allows it to re-use
511 * an existing Loader's data if there already is one, so that for example
512 * when an {@link Activity} is re-created after a configuration change it
513 * does not need to re-create its loaders.
514 *
515 * <p>Note that in the case where an existing Loader is re-used, the
516 * <var>args</var> given here <em>will be ignored</em> because you will
517 * continue using the previous Loader.
518 *
519 * @param id A unique (to this LoaderManager instance) identifier under
520 * which to manage the new Loader.
521 * @param args Optional arguments that will be propagated to
522 * {@link LoaderCallbacks#onCreateLoader(int, Bundle) LoaderCallbacks.onCreateLoader()}.
523 * @param callback Interface implementing management of this Loader. Required.
524 * Its onCreateLoader() method will be called while inside of the function to
525 * instantiate the Loader object.
526 */
Dianne Hackborn2707d602010-07-09 18:01:20 -0700527 @SuppressWarnings("unchecked")
528 public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800529 if (mCreatingLoader) {
530 throw new IllegalStateException("Called while creating a loader");
531 }
532
Dianne Hackborn2707d602010-07-09 18:01:20 -0700533 LoaderInfo info = mLoaders.get(id);
534
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800535 if (DEBUG) Log.v(TAG, "initLoader in " + this + ": args=" + args);
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700536
Dianne Hackborn2707d602010-07-09 18:01:20 -0700537 if (info == null) {
538 // Loader doesn't already exist; create.
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800539 info = createAndInstallLoader(id, args, (LoaderManager.LoaderCallbacks<Object>)callback);
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800540 if (DEBUG) Log.v(TAG, " Created new loader " + info);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700541 } else {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800542 if (DEBUG) Log.v(TAG, " Re-using existing loader " + info);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700543 info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
544 }
545
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800546 if (info.mHaveData && mStarted) {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700547 // If the loader has already generated its data, report it now.
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700548 info.callOnLoadFinished(info.mLoader, info.mData);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700549 }
550
551 return (Loader<D>)info.mLoader;
552 }
553
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800554 /**
555 * Call to re-create the Loader associated with a particular ID. If there
556 * is currently a Loader associated with this ID, it will be
557 * canceled/stopped/destroyed as appropriate. A new Loader with the given
558 * arguments will be created and its data delivered to you once available.
559 *
560 * <p>This function does some throttling of Loaders. If too many Loaders
561 * have been created for the given ID but not yet generated their data,
562 * new calls to this function will create and return a new Loader but not
563 * actually start it until some previous loaders have completed.
564 *
565 * <p>After calling this function, any previous Loaders associated with
566 * this ID will be considered invalid, and you will receive no further
567 * data updates from them.
568 *
569 * @param id A unique (to this LoaderManager instance) identifier under
570 * which to manage the new Loader.
571 * @param args Optional arguments that will be propagated to
572 * {@link LoaderCallbacks#onCreateLoader(int, Bundle) LoaderCallbacks.onCreateLoader()}.
573 * @param callback Interface implementing management of this Loader. Required.
574 * Its onCreateLoader() method will be called while inside of the function to
575 * instantiate the Loader object.
576 */
Dianne Hackbornc8017682010-07-06 13:34:38 -0700577 @SuppressWarnings("unchecked")
Dianne Hackborn2707d602010-07-09 18:01:20 -0700578 public <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800579 if (mCreatingLoader) {
580 throw new IllegalStateException("Called while creating a loader");
581 }
582
Dianne Hackbornc8017682010-07-06 13:34:38 -0700583 LoaderInfo info = mLoaders.get(id);
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800584 if (DEBUG) Log.v(TAG, "restartLoader in " + this + ": args=" + args);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700585 if (info != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700586 LoaderInfo inactive = mInactiveLoaders.get(id);
587 if (inactive != null) {
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800588 if (info.mHaveData) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700589 // This loader now has data... we are probably being
590 // called from within onLoadComplete, where we haven't
591 // yet destroyed the last inactive loader. So just do
592 // that now.
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800593 if (DEBUG) Log.v(TAG, " Removing last inactive loader: " + info);
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800594 inactive.mDeliveredData = false;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700595 inactive.destroy();
Dianne Hackborn260c3c72011-01-30 16:55:55 -0800596 info.mLoader.abandon();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700597 mInactiveLoaders.put(id, info);
598 } else {
599 // We already have an inactive loader for this ID that we are
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800600 // waiting for! What to do, what to do...
601 if (!info.mStarted) {
602 // The current Loader has not been started... we thus
603 // have no reason to keep it around, so bam, slam,
604 // thank-you-ma'am.
605 if (DEBUG) Log.v(TAG, " Current loader is stopped; replacing");
606 mLoaders.put(id, null);
607 info.destroy();
608 } else {
609 // Now we have three active loaders... we'll queue
610 // up this request to be processed once one of the other loaders
611 // finishes.
612 if (info.mPendingLoader != null) {
613 if (DEBUG) Log.v(TAG, " Removing pending loader: " + info.mPendingLoader);
614 info.mPendingLoader.destroy();
615 info.mPendingLoader = null;
616 }
617 if (DEBUG) Log.v(TAG, " Enqueuing as new pending loader");
618 info.mPendingLoader = createLoader(id, args,
619 (LoaderManager.LoaderCallbacks<Object>)callback);
620 return (Loader<D>)info.mPendingLoader.mLoader;
621 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700622 }
Dianne Hackborn2707d602010-07-09 18:01:20 -0700623 } else {
624 // Keep track of the previous instance of this loader so we can destroy
625 // it when the new one completes.
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800626 if (DEBUG) Log.v(TAG, " Making last loader inactive: " + info);
Dianne Hackborn260c3c72011-01-30 16:55:55 -0800627 info.mLoader.abandon();
Dianne Hackborn2707d602010-07-09 18:01:20 -0700628 mInactiveLoaders.put(id, info);
629 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700630 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700631
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800632 info = createAndInstallLoader(id, args, (LoaderManager.LoaderCallbacks<Object>)callback);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700633 return (Loader<D>)info.mLoader;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700634 }
635
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800636 /**
637 * Rip down, tear apart, shred to pieces a current Loader ID. After returning
638 * from this function, any Loader objects associated with this ID are
639 * destroyed. Any data associated with them is destroyed. You better not
640 * be using it when you do this.
641 * @param id Identifier of the Loader to be destroyed.
642 */
Dianne Hackbornc9189352010-12-15 14:57:25 -0800643 public void destroyLoader(int id) {
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800644 if (mCreatingLoader) {
645 throw new IllegalStateException("Called while creating a loader");
646 }
647
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800648 if (DEBUG) Log.v(TAG, "destroyLoader in " + this + " of " + id);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700649 int idx = mLoaders.indexOfKey(id);
650 if (idx >= 0) {
651 LoaderInfo info = mLoaders.valueAt(idx);
652 mLoaders.removeAt(idx);
Dianne Hackborn4911b782010-07-15 12:54:39 -0700653 info.destroy();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700654 }
Dianne Hackbornf73c75c2010-12-17 16:54:05 -0800655 idx = mInactiveLoaders.indexOfKey(id);
656 if (idx >= 0) {
657 LoaderInfo info = mInactiveLoaders.valueAt(idx);
658 mInactiveLoaders.removeAt(idx);
659 info.destroy();
660 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700661 }
662
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800663 /**
664 * Return the most recent Loader object associated with the
665 * given ID.
666 */
Dianne Hackbornc8017682010-07-06 13:34:38 -0700667 @SuppressWarnings("unchecked")
668 public <D> Loader<D> getLoader(int id) {
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800669 if (mCreatingLoader) {
670 throw new IllegalStateException("Called while creating a loader");
671 }
672
Dianne Hackbornc8017682010-07-06 13:34:38 -0700673 LoaderInfo loaderInfo = mLoaders.get(id);
674 if (loaderInfo != null) {
Dianne Hackborn6e1bf6a2011-01-20 13:40:19 -0800675 if (loaderInfo.mPendingLoader != null) {
676 return (Loader<D>)loaderInfo.mPendingLoader.mLoader;
677 }
678 return (Loader<D>)loaderInfo.mLoader;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700679 }
680 return null;
681 }
682
683 void doStart() {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800684 if (DEBUG) Log.v(TAG, "Starting in " + this);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700685 if (mStarted) {
686 RuntimeException e = new RuntimeException("here");
687 e.fillInStackTrace();
688 Log.w(TAG, "Called doStart when already started: " + this, e);
689 return;
690 }
691
Dianne Hackbornc9189352010-12-15 14:57:25 -0800692 mStarted = true;
693
Dianne Hackbornc8017682010-07-06 13:34:38 -0700694 // Call out to sub classes so they can start their loaders
695 // Let the existing loaders know that we want to be notified when a load is complete
696 for (int i = mLoaders.size()-1; i >= 0; i--) {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700697 mLoaders.valueAt(i).start();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700698 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700699 }
700
701 void doStop() {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800702 if (DEBUG) Log.v(TAG, "Stopping in " + this);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700703 if (!mStarted) {
704 RuntimeException e = new RuntimeException("here");
705 e.fillInStackTrace();
706 Log.w(TAG, "Called doStop when not started: " + this, e);
707 return;
708 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700709
Dianne Hackbornc8017682010-07-06 13:34:38 -0700710 for (int i = mLoaders.size()-1; i >= 0; i--) {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700711 mLoaders.valueAt(i).stop();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700712 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700713 mStarted = false;
714 }
715
Dianne Hackborn2707d602010-07-09 18:01:20 -0700716 void doRetain() {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800717 if (DEBUG) Log.v(TAG, "Retaining in " + this);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700718 if (!mStarted) {
719 RuntimeException e = new RuntimeException("here");
720 e.fillInStackTrace();
721 Log.w(TAG, "Called doRetain when not started: " + this, e);
722 return;
723 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700724
Dianne Hackborn2707d602010-07-09 18:01:20 -0700725 mRetaining = true;
726 mStarted = false;
727 for (int i = mLoaders.size()-1; i >= 0; i--) {
728 mLoaders.valueAt(i).retain();
729 }
730 }
731
732 void finishRetain() {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800733 if (mRetaining) {
734 if (DEBUG) Log.v(TAG, "Finished Retaining in " + this);
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700735
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800736 mRetaining = false;
737 for (int i = mLoaders.size()-1; i >= 0; i--) {
738 mLoaders.valueAt(i).finishRetain();
739 }
Dianne Hackborn2707d602010-07-09 18:01:20 -0700740 }
741 }
742
Dianne Hackbornc8017682010-07-06 13:34:38 -0700743 void doDestroy() {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700744 if (!mRetaining) {
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800745 if (DEBUG) Log.v(TAG, "Destroying Active in " + this);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700746 for (int i = mLoaders.size()-1; i >= 0; i--) {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700747 mLoaders.valueAt(i).destroy();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700748 }
749 }
Dianne Hackborn2707d602010-07-09 18:01:20 -0700750
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800751 if (DEBUG) Log.v(TAG, "Destroying Inactive in " + this);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700752 for (int i = mInactiveLoaders.size()-1; i >= 0; i--) {
753 mInactiveLoaders.valueAt(i).destroy();
754 }
755 mInactiveLoaders.clear();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700756 }
Dianne Hackborn30d71892010-12-11 10:37:55 -0800757
758 @Override
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800759 public String toString() {
760 StringBuilder sb = new StringBuilder(128);
761 sb.append("LoaderManager{");
762 sb.append(Integer.toHexString(System.identityHashCode(this)));
763 sb.append(" in ");
764 DebugUtils.buildShortClassTag(mActivity, sb);
765 sb.append("}}");
766 return sb.toString();
767 }
768
769 @Override
Dianne Hackborn30d71892010-12-11 10:37:55 -0800770 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
771 if (mLoaders.size() > 0) {
772 writer.print(prefix); writer.println("Active Loaders:");
773 String innerPrefix = prefix + " ";
774 for (int i=0; i < mLoaders.size(); i++) {
775 LoaderInfo li = mLoaders.valueAt(i);
776 writer.print(prefix); writer.print(" #"); writer.print(mLoaders.keyAt(i));
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800777 writer.print(": "); writer.println(li.toString());
Dianne Hackborn30d71892010-12-11 10:37:55 -0800778 li.dump(innerPrefix, fd, writer, args);
779 }
780 }
781 if (mInactiveLoaders.size() > 0) {
782 writer.print(prefix); writer.println("Inactive Loaders:");
783 String innerPrefix = prefix + " ";
784 for (int i=0; i < mInactiveLoaders.size(); i++) {
785 LoaderInfo li = mInactiveLoaders.valueAt(i);
786 writer.print(prefix); writer.print(" #"); writer.print(mInactiveLoaders.keyAt(i));
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800787 writer.print(": "); writer.println(li.toString());
Dianne Hackborn30d71892010-12-11 10:37:55 -0800788 li.dump(innerPrefix, fd, writer, args);
789 }
790 }
791 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700792}