LoaderManager.java revision fb3cffeb35368da22f99b85d45039c4e6e471c06
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import android.content.Loader;
20import android.os.Bundle;
21import android.util.Log;
22import android.util.SparseArray;
23
24/**
25 * Interface associated with an {@link Activity} or {@link Fragment} for managing
26 * one or more {@link android.content.Loader} instances associated with it.
27 */
28public interface LoaderManager {
29    /**
30     * Callback interface for a client to interact with the manager.
31     */
32    public interface LoaderCallbacks<D> {
33        /**
34         * Instantiate and return a new Loader for the given ID.
35         *
36         * @param id The ID whose loader is to be created.
37         * @param args Any arguments supplied by the caller.
38         * @return Return a new Loader instance that is ready to start loading.
39         */
40        public Loader<D> onCreateLoader(int id, Bundle args);
41
42        /**
43         * Called when a previously created loader has finished its load.  Note
44         * that normally an application is <em>not</em> allowed to commit fragment
45         * transactions while in this call, since it can happen after an
46         * activity's state is saved.  See {@link FragmentManager#openTransaction()
47         * FragmentManager.openTransaction()} for further discussion on this.
48         *
49         * @param loader The Loader that has finished.
50         * @param data The data generated by the Loader.
51         */
52        public void onLoadFinished(Loader<D> loader, D data);
53    }
54
55    /**
56     * Ensures a loader is initialized and active.  If the loader doesn't
57     * already exist, one is created and (if the activity/fragment is currently
58     * started) starts the loader.  Otherwise the last created
59     * loader is re-used.
60     *
61     * <p>In either case, the given callback is associated with the loader, and
62     * will be called as the loader state changes.  If at the point of call
63     * the caller is in its started state, and the requested loader
64     * already exists and has generated its data, then
65     * callback. {@link LoaderCallbacks#onLoadFinished} will
66     * be called immediately (inside of this function), so you must be prepared
67     * for this to happen.
68     */
69    public <D> Loader<D> initLoader(int id, Bundle args,
70            LoaderManager.LoaderCallbacks<D> callback);
71
72    /**
73     * Creates a new loader in this manager, registers the callbacks to it,
74     * and (if the activity/fragment is currently started) starts loading it.
75     * If a loader with the same id has previously been
76     * started it will automatically be destroyed when the new loader completes
77     * its work. The callback will be delivered before the old loader
78     * is destroyed.
79     */
80    public <D> Loader<D> restartLoader(int id, Bundle args,
81            LoaderManager.LoaderCallbacks<D> callback);
82
83    /**
84     * Stops and removes the loader with the given ID.
85     */
86    public void stopLoader(int id);
87
88    /**
89     * Return the Loader with the given id or null if no matching Loader
90     * is found.
91     */
92    public <D> Loader<D> getLoader(int id);
93}
94
95class LoaderManagerImpl implements LoaderManager {
96    static final String TAG = "LoaderManagerImpl";
97    static final boolean DEBUG = true;
98
99    // These are the currently active loaders.  A loader is here
100    // from the time its load is started until it has been explicitly
101    // stopped or restarted by the application.
102    final SparseArray<LoaderInfo> mLoaders = new SparseArray<LoaderInfo>();
103
104    // These are previously run loaders.  This list is maintained internally
105    // to avoid destroying a loader while an application is still using it.
106    // It allows an application to restart a loader, but continue using its
107    // previously run loader until the new loader's data is available.
108    final SparseArray<LoaderInfo> mInactiveLoaders = new SparseArray<LoaderInfo>();
109
110    Activity mActivity;
111    boolean mStarted;
112    boolean mRetaining;
113    boolean mRetainingStarted;
114
115    final class LoaderInfo implements Loader.OnLoadCompleteListener<Object> {
116        final int mId;
117        final Bundle mArgs;
118        LoaderManager.LoaderCallbacks<Object> mCallbacks;
119        Loader<Object> mLoader;
120        Object mData;
121        boolean mStarted;
122        boolean mRetaining;
123        boolean mRetainingStarted;
124        boolean mDestroyed;
125        boolean mListenerRegistered;
126
127        public LoaderInfo(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callbacks) {
128            mId = id;
129            mArgs = args;
130            mCallbacks = callbacks;
131        }
132
133        void start() {
134            if (mRetaining && mRetainingStarted) {
135                // Our owner is started, but we were being retained from a
136                // previous instance in the started state...  so there is really
137                // nothing to do here, since the loaders are still started.
138                mStarted = true;
139                return;
140            }
141
142            if (mStarted) {
143                // If loader already started, don't restart.
144                return;
145            }
146
147            if (DEBUG) Log.v(TAG, "  Starting: " + this);
148            if (mLoader == null && mCallbacks != null) {
149               mLoader = mCallbacks.onCreateLoader(mId, mArgs);
150            }
151            if (mLoader != null) {
152                if (!mListenerRegistered) {
153                    mLoader.registerListener(mId, this);
154                    mListenerRegistered = true;
155                }
156                mLoader.startLoading();
157                mStarted = true;
158            }
159        }
160
161        void retain() {
162            if (DEBUG) Log.v(TAG, "  Retaining: " + this);
163            mRetaining = true;
164            mRetainingStarted = mStarted;
165            mStarted = false;
166            mCallbacks = null;
167        }
168
169        void finishRetain() {
170            if (mRetaining) {
171                if (DEBUG) Log.v(TAG, "  Finished Retaining: " + this);
172                mRetaining = false;
173                if (mStarted != mRetainingStarted) {
174                    if (!mStarted) {
175                        // This loader was retained in a started state, but
176                        // at the end of retaining everything our owner is
177                        // no longer started...  so make it stop.
178                        stop();
179                    }
180                }
181                if (mStarted && mData != null) {
182                    // This loader was retained, and now at the point of
183                    // finishing the retain we find we remain started, have
184                    // our data, and the owner has a new callback...  so
185                    // let's deliver the data now.
186                    callOnLoadFinished(mLoader, mData);
187                }
188            }
189        }
190
191        void stop() {
192            if (DEBUG) Log.v(TAG, "  Stopping: " + this);
193            mStarted = false;
194            if (!mRetaining) {
195                if (mLoader != null && mListenerRegistered) {
196                    // Let the loader know we're done with it
197                    mListenerRegistered = false;
198                    mLoader.unregisterListener(this);
199                    mLoader.stopLoading();
200                }
201                mData = null;
202            }
203        }
204
205        void destroy() {
206            if (DEBUG) Log.v(TAG, "  Destroying: " + this);
207            mDestroyed = true;
208            mCallbacks = null;
209            if (mLoader != null) {
210                if (mListenerRegistered) {
211                    mListenerRegistered = false;
212                    mLoader.unregisterListener(this);
213                }
214                mLoader.destroy();
215            }
216        }
217
218        @Override public void onLoadComplete(Loader<Object> loader, Object data) {
219            if (DEBUG) Log.v(TAG, "onLoadComplete: " + this + " mDestroyed=" + mDestroyed);
220
221            if (mDestroyed) {
222                return;
223            }
224
225            // Notify of the new data so the app can switch out the old data before
226            // we try to destroy it.
227            mData = data;
228            callOnLoadFinished(loader, data);
229
230            if (DEBUG) Log.v(TAG, "onLoadFinished returned: " + this);
231
232            // We have now given the application the new loader with its
233            // loaded data, so it should have stopped using the previous
234            // loader.  If there is a previous loader on the inactive list,
235            // clean it up.
236            LoaderInfo info = mInactiveLoaders.get(mId);
237            if (info != null && info != this) {
238                info.destroy();
239                mInactiveLoaders.remove(mId);
240            }
241        }
242
243        void callOnLoadFinished(Loader<Object> loader, Object data) {
244            if (mCallbacks != null) {
245                String lastBecause = null;
246                if (mActivity != null) {
247                    lastBecause = mActivity.mFragments.mNoTransactionsBecause;
248                    mActivity.mFragments.mNoTransactionsBecause = "onLoadFinished";
249                }
250                try {
251                    mCallbacks.onLoadFinished(loader, data);
252                } finally {
253                    if (mActivity != null) {
254                        mActivity.mFragments.mNoTransactionsBecause = lastBecause;
255                    }
256                }
257            }
258        }
259
260        @Override
261        public String toString() {
262            StringBuilder sb = new StringBuilder(64);
263            sb.append("LoaderInfo{");
264            sb.append(Integer.toHexString(System.identityHashCode(this)));
265            sb.append(" #");
266            sb.append(mId);
267            if (mArgs != null) {
268                sb.append(" ");
269                sb.append(mArgs.toString());
270            }
271            sb.append("}");
272            return sb.toString();
273        }
274    }
275
276    LoaderManagerImpl(Activity activity, boolean started) {
277        mActivity = activity;
278        mStarted = started;
279    }
280
281    void updateActivity(Activity activity) {
282        mActivity = activity;
283    }
284
285    private LoaderInfo createLoader(int id, Bundle args,
286            LoaderManager.LoaderCallbacks<Object> callback) {
287        LoaderInfo info = new LoaderInfo(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
288        mLoaders.put(id, info);
289        Loader<Object> loader = callback.onCreateLoader(id, args);
290        info.mLoader = (Loader<Object>)loader;
291        if (mStarted) {
292            // The activity will start all existing loaders in it's onStart(),
293            // so only start them here if we're past that point of the activitiy's
294            // life cycle
295            info.start();
296        }
297        return info;
298    }
299
300    @SuppressWarnings("unchecked")
301    public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
302        LoaderInfo info = mLoaders.get(id);
303
304        if (DEBUG) Log.v(TAG, "initLoader in " + this + ": cur=" + info);
305
306        if (info == null) {
307            // Loader doesn't already exist; create.
308            info = createLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
309        } else {
310            info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
311        }
312
313        if (info.mData != null && mStarted) {
314            // If the loader has already generated its data, report it now.
315            info.callOnLoadFinished(info.mLoader, info.mData);
316        }
317
318        return (Loader<D>)info.mLoader;
319    }
320
321    @SuppressWarnings("unchecked")
322    public <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
323        LoaderInfo info = mLoaders.get(id);
324        if (DEBUG) Log.v(TAG, "restartLoader in " + this + ": cur=" + info);
325        if (info != null) {
326            LoaderInfo inactive = mInactiveLoaders.get(id);
327            if (inactive != null) {
328                if (info.mData != null) {
329                    // This loader now has data...  we are probably being
330                    // called from within onLoadComplete, where we haven't
331                    // yet destroyed the last inactive loader.  So just do
332                    // that now.
333                    if (DEBUG) Log.v(TAG, "  Removing last inactive loader in " + this);
334                    inactive.destroy();
335                    mInactiveLoaders.put(id, info);
336                } else {
337                    // We already have an inactive loader for this ID that we are
338                    // waiting for!  Now we have three active loaders... let's just
339                    // drop the one in the middle, since we are still waiting for
340                    // its result but that result is already out of date.
341                    if (DEBUG) Log.v(TAG, "  Removing intermediate loader in " + this);
342                    info.destroy();
343                }
344            } else {
345                // Keep track of the previous instance of this loader so we can destroy
346                // it when the new one completes.
347                if (DEBUG) Log.v(TAG, "  Making inactive: " + info);
348                mInactiveLoaders.put(id, info);
349            }
350        }
351
352        info = createLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
353        return (Loader<D>)info.mLoader;
354    }
355
356    public void stopLoader(int id) {
357        if (DEBUG) Log.v(TAG, "stopLoader in " + this + " of " + id);
358        int idx = mLoaders.indexOfKey(id);
359        if (idx >= 0) {
360            LoaderInfo info = mLoaders.valueAt(idx);
361            mLoaders.removeAt(idx);
362            info.destroy();
363        }
364    }
365
366    @SuppressWarnings("unchecked")
367    public <D> Loader<D> getLoader(int id) {
368        LoaderInfo loaderInfo = mLoaders.get(id);
369        if (loaderInfo != null) {
370            return (Loader<D>)mLoaders.get(id).mLoader;
371        }
372        return null;
373    }
374
375    void doStart() {
376        if (DEBUG) Log.v(TAG, "Starting: " + this);
377        if (mStarted) {
378            RuntimeException e = new RuntimeException("here");
379            e.fillInStackTrace();
380            Log.w(TAG, "Called doStart when already started: " + this, e);
381            return;
382        }
383
384        // Call out to sub classes so they can start their loaders
385        // Let the existing loaders know that we want to be notified when a load is complete
386        for (int i = mLoaders.size()-1; i >= 0; i--) {
387            mLoaders.valueAt(i).start();
388        }
389        mStarted = true;
390    }
391
392    void doStop() {
393        if (DEBUG) Log.v(TAG, "Stopping: " + this);
394        if (!mStarted) {
395            RuntimeException e = new RuntimeException("here");
396            e.fillInStackTrace();
397            Log.w(TAG, "Called doStop when not started: " + this, e);
398            return;
399        }
400
401        for (int i = mLoaders.size()-1; i >= 0; i--) {
402            mLoaders.valueAt(i).stop();
403        }
404        mStarted = false;
405    }
406
407    void doRetain() {
408        if (DEBUG) Log.v(TAG, "Retaining: " + this);
409        if (!mStarted) {
410            RuntimeException e = new RuntimeException("here");
411            e.fillInStackTrace();
412            Log.w(TAG, "Called doRetain when not started: " + this, e);
413            return;
414        }
415
416        mRetaining = true;
417        mStarted = false;
418        for (int i = mLoaders.size()-1; i >= 0; i--) {
419            mLoaders.valueAt(i).retain();
420        }
421    }
422
423    void finishRetain() {
424        if (DEBUG) Log.v(TAG, "Finished Retaining: " + this);
425
426        mRetaining = false;
427        for (int i = mLoaders.size()-1; i >= 0; i--) {
428            mLoaders.valueAt(i).finishRetain();
429        }
430    }
431
432    void doDestroy() {
433        if (!mRetaining) {
434            if (DEBUG) Log.v(TAG, "Destroying Active: " + this);
435            for (int i = mLoaders.size()-1; i >= 0; i--) {
436                mLoaders.valueAt(i).destroy();
437            }
438        }
439
440        if (DEBUG) Log.v(TAG, "Destroying Inactive: " + this);
441        for (int i = mInactiveLoaders.size()-1; i >= 0; i--) {
442            mInactiveLoaders.valueAt(i).destroy();
443        }
444        mInactiveLoaders.clear();
445    }
446}
447