• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 
17 package android.support.v4.content;
18 
19 import android.content.Context;
20 import android.database.ContentObserver;
21 import android.os.Handler;
22 import android.support.v4.util.DebugUtils;
23 
24 import java.io.FileDescriptor;
25 import java.io.PrintWriter;
26 
27 /**
28  * Static library support version of the framework's {@link android.content.Loader}.
29  * Used to write apps that run on platforms prior to Android 3.0.  When running
30  * on Android 3.0 or above, this implementation is still used; it does not try
31  * to switch to the framework's implementation.  See the framework SDK
32  * documentation for a class overview.
33  */
34 public class Loader<D> {
35     int mId;
36     OnLoadCompleteListener<D> mListener;
37     Context mContext;
38     boolean mStarted = false;
39     boolean mAbandoned = false;
40     boolean mReset = true;
41     boolean mContentChanged = false;
42     boolean mProcessingChange = false;
43 
44     /**
45      * An implementation of a ContentObserver that takes care of connecting
46      * it to the Loader to have the loader re-load its data when the observer
47      * is told it has changed.  You do not normally need to use this yourself;
48      * it is used for you by {@link android.support.v4.content.CursorLoader}
49      * to take care of executing an update when the cursor's backing data changes.
50      */
51     public final class ForceLoadContentObserver extends ContentObserver {
ForceLoadContentObserver()52         public ForceLoadContentObserver() {
53             super(new Handler());
54         }
55 
56         @Override
deliverSelfNotifications()57         public boolean deliverSelfNotifications() {
58             return true;
59         }
60 
61         @Override
onChange(boolean selfChange)62         public void onChange(boolean selfChange) {
63             onContentChanged();
64         }
65     }
66 
67     /**
68      * Interface that is implemented to discover when a Loader has finished
69      * loading its data.  You do not normally need to implement this yourself;
70      * it is used in the implementation of {@link android.support.v4.app.LoaderManager}
71      * to find out when a Loader it is managing has completed so that this can
72      * be reported to its client.  This interface should only be used if a
73      * Loader is not being used in conjunction with LoaderManager.
74      */
75     public interface OnLoadCompleteListener<D> {
76         /**
77          * Called on the thread that created the Loader when the load is complete.
78          *
79          * @param loader the loader that completed the load
80          * @param data the result of the load
81          */
onLoadComplete(Loader<D> loader, D data)82         public void onLoadComplete(Loader<D> loader, D data);
83     }
84 
85     /**
86      * Stores away the application context associated with context. Since Loaders can be used
87      * across multiple activities it's dangerous to store the context directly.
88      *
89      * @param context used to retrieve the application context.
90      */
Loader(Context context)91     public Loader(Context context) {
92         mContext = context.getApplicationContext();
93     }
94 
95     /**
96      * Sends the result of the load to the registered listener. Should only be called by subclasses.
97      *
98      * Must be called from the process's main thread.
99      *
100      * @param data the result of the load
101      */
deliverResult(D data)102     public void deliverResult(D data) {
103         if (mListener != null) {
104             mListener.onLoadComplete(this, data);
105         }
106     }
107 
108     /**
109      * @return an application context retrieved from the Context passed to the constructor.
110      */
getContext()111     public Context getContext() {
112         return mContext;
113     }
114 
115     /**
116      * @return the ID of this loader
117      */
getId()118     public int getId() {
119         return mId;
120     }
121 
122     /**
123      * Registers a class that will receive callbacks when a load is complete.
124      * The callback will be called on the process's main thread so it's safe to
125      * pass the results to widgets.
126      *
127      * <p>Must be called from the process's main thread.
128      */
registerListener(int id, OnLoadCompleteListener<D> listener)129     public void registerListener(int id, OnLoadCompleteListener<D> listener) {
130         if (mListener != null) {
131             throw new IllegalStateException("There is already a listener registered");
132         }
133         mListener = listener;
134         mId = id;
135     }
136 
137     /**
138      * Remove a listener that was previously added with {@link #registerListener}.
139      *
140      * Must be called from the process's main thread.
141      */
unregisterListener(OnLoadCompleteListener<D> listener)142     public void unregisterListener(OnLoadCompleteListener<D> listener) {
143         if (mListener == null) {
144             throw new IllegalStateException("No listener register");
145         }
146         if (mListener != listener) {
147             throw new IllegalArgumentException("Attempting to unregister the wrong listener");
148         }
149         mListener = null;
150     }
151 
152     /**
153      * Return whether this load has been started.  That is, its {@link #startLoading()}
154      * has been called and no calls to {@link #stopLoading()} or
155      * {@link #reset()} have yet been made.
156      */
isStarted()157     public boolean isStarted() {
158         return mStarted;
159     }
160 
161     /**
162      * Return whether this loader has been abandoned.  In this state, the
163      * loader <em>must not</em> report any new data, and <em>must</em> keep
164      * its last reported data valid until it is finally reset.
165      */
isAbandoned()166     public boolean isAbandoned() {
167         return mAbandoned;
168     }
169 
170     /**
171      * Return whether this load has been reset.  That is, either the loader
172      * has not yet been started for the first time, or its {@link #reset()}
173      * has been called.
174      */
isReset()175     public boolean isReset() {
176         return mReset;
177     }
178 
179     /**
180      * Starts an asynchronous load of the Loader's data. When the result
181      * is ready the callbacks will be called on the process's main thread.
182      * If a previous load has been completed and is still valid
183      * the result may be passed to the callbacks immediately.
184      * The loader will monitor the source of
185      * the data set and may deliver future callbacks if the source changes.
186      * Calling {@link #stopLoading} will stop the delivery of callbacks.
187      *
188      * <p>This updates the Loader's internal state so that
189      * {@link #isStarted()} and {@link #isReset()} will return the correct
190      * values, and then calls the implementation's {@link #onStartLoading()}.
191      *
192      * <p>Must be called from the process's main thread.
193      */
startLoading()194     public final void startLoading() {
195         mStarted = true;
196         mReset = false;
197         mAbandoned = false;
198         onStartLoading();
199     }
200 
201     /**
202      * Subclasses must implement this to take care of loading their data,
203      * as per {@link #startLoading()}.  This is not called by clients directly,
204      * but as a result of a call to {@link #startLoading()}.
205      */
onStartLoading()206     protected void onStartLoading() {
207     }
208 
209     /**
210      * Force an asynchronous load. Unlike {@link #startLoading()} this will ignore a previously
211      * loaded data set and load a new one.  This simply calls through to the
212      * implementation's {@link #onForceLoad()}.  You generally should only call this
213      * when the loader is started -- that is, {@link #isStarted()} returns true.
214      *
215      * <p>Must be called from the process's main thread.
216      */
forceLoad()217     public void forceLoad() {
218         onForceLoad();
219     }
220 
221     /**
222      * Subclasses must implement this to take care of requests to {@link #forceLoad()}.
223      * This will always be called from the process's main thread.
224      */
onForceLoad()225     protected void onForceLoad() {
226     }
227 
228     /**
229      * Stops delivery of updates until the next time {@link #startLoading()} is called.
230      * Implementations should <em>not</em> invalidate their data at this point --
231      * clients are still free to use the last data the loader reported.  They will,
232      * however, typically stop reporting new data if the data changes; they can
233      * still monitor for changes, but must not report them to the client until and
234      * if {@link #startLoading()} is later called.
235      *
236      * <p>This updates the Loader's internal state so that
237      * {@link #isStarted()} will return the correct
238      * value, and then calls the implementation's {@link #onStopLoading()}.
239      *
240      * <p>Must be called from the process's main thread.
241      */
stopLoading()242     public void stopLoading() {
243         mStarted = false;
244         onStopLoading();
245     }
246 
247     /**
248      * Subclasses must implement this to take care of stopping their loader,
249      * as per {@link #stopLoading()}.  This is not called by clients directly,
250      * but as a result of a call to {@link #stopLoading()}.
251      * This will always be called from the process's main thread.
252      */
onStopLoading()253     protected void onStopLoading() {
254     }
255 
256     /**
257      * Tell the Loader that it is being abandoned.  This is called prior
258      * to {@link #reset} to have it retain its current data but not report
259      * any new data.
260      */
abandon()261     public void abandon() {
262         mAbandoned = true;
263         onAbandon();
264     }
265 
266     /**
267      * Subclasses implement this to take care of being abandoned.  This is
268      * an optional intermediate state prior to {@link #onReset()} -- it means that
269      * the client is no longer interested in any new data from the loader,
270      * so the loader must not report any further updates.  However, the
271      * loader <em>must</em> keep its last reported data valid until the final
272      * {@link #onReset()} happens.  You can retrieve the current abandoned
273      * state with {@link #isAbandoned}.
274      */
onAbandon()275     protected void onAbandon() {
276     }
277 
278     /**
279      * Resets the state of the Loader.  The Loader should at this point free
280      * all of its resources, since it may never be called again; however, its
281      * {@link #startLoading()} may later be called at which point it must be
282      * able to start running again.
283      *
284      * <p>This updates the Loader's internal state so that
285      * {@link #isStarted()} and {@link #isReset()} will return the correct
286      * values, and then calls the implementation's {@link #onReset()}.
287      *
288      * <p>Must be called from the process's main thread.
289      */
reset()290     public void reset() {
291         onReset();
292         mReset = true;
293         mStarted = false;
294         mAbandoned = false;
295         mContentChanged = false;
296         mProcessingChange = false;
297     }
298 
299     /**
300      * Subclasses must implement this to take care of resetting their loader,
301      * as per {@link #reset()}.  This is not called by clients directly,
302      * but as a result of a call to {@link #reset()}.
303      * This will always be called from the process's main thread.
304      */
onReset()305     protected void onReset() {
306     }
307 
308     /**
309      * Take the current flag indicating whether the loader's content had
310      * changed while it was stopped.  If it had, true is returned and the
311      * flag is cleared.
312      */
takeContentChanged()313     public boolean takeContentChanged() {
314         boolean res = mContentChanged;
315         mContentChanged = false;
316         mProcessingChange |= res;
317         return res;
318     }
319 
320     /**
321      * Commit that you have actually fully processed a content change that
322      * was returned by {@link #takeContentChanged}.  This is for use with
323      * {@link #rollbackContentChanged()} to handle situations where a load
324      * is cancelled.  Call this when you have completely processed a load
325      * without it being cancelled.
326      */
commitContentChanged()327     public void commitContentChanged() {
328         mProcessingChange = false;
329     }
330 
331     /**
332      * Report that you have abandoned the processing of a content change that
333      * was returned by {@link #takeContentChanged()} and would like to rollback
334      * to the state where there is again a pending content change.  This is
335      * to handle the case where a data load due to a content change has been
336      * canceled before its data was delivered back to the loader.
337      */
rollbackContentChanged()338     public void rollbackContentChanged() {
339         if (mProcessingChange) {
340             mContentChanged = true;
341         }
342     }
343 
344     /**
345      * Called when {@link ForceLoadContentObserver} detects a change.  The
346      * default implementation checks to see if the loader is currently started;
347      * if so, it simply calls {@link #forceLoad()}; otherwise, it sets a flag
348      * so that {@link #takeContentChanged()} returns true.
349      *
350      * <p>Must be called from the process's main thread.
351      */
onContentChanged()352     public void onContentChanged() {
353         if (mStarted) {
354             forceLoad();
355         } else {
356             // This loader has been stopped, so we don't want to load
357             // new data right now...  but keep track of it changing to
358             // refresh later if we start again.
359             mContentChanged = true;
360         }
361     }
362 
363     /**
364      * For debugging, converts an instance of the Loader's data class to
365      * a string that can be printed.  Must handle a null data.
366      */
dataToString(D data)367     public String dataToString(D data) {
368         StringBuilder sb = new StringBuilder(64);
369         DebugUtils.buildShortClassTag(data, sb);
370         sb.append("}");
371         return sb.toString();
372     }
373 
374     @Override
toString()375     public String toString() {
376         StringBuilder sb = new StringBuilder(64);
377         DebugUtils.buildShortClassTag(this, sb);
378         sb.append(" id=");
379         sb.append(mId);
380         sb.append("}");
381         return sb.toString();
382     }
383 
384     /**
385      * Print the Loader's state into the given stream.
386      *
387      * @param prefix Text to print at the front of each line.
388      * @param fd The raw file descriptor that the dump is being sent to.
389      * @param writer A PrintWriter to which the dump is to be set.
390      * @param args Additional arguments to the dump request.
391      */
dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)392     public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
393         writer.print(prefix); writer.print("mId="); writer.print(mId);
394                 writer.print(" mListener="); writer.println(mListener);
395         if (mStarted || mContentChanged || mProcessingChange) {
396             writer.print(prefix); writer.print("mStarted="); writer.print(mStarted);
397                     writer.print(" mContentChanged="); writer.print(mContentChanged);
398                     writer.print(" mProcessingChange="); writer.println(mProcessingChange);
399         }
400         if (mAbandoned || mReset) {
401             writer.print(prefix); writer.print("mAbandoned="); writer.print(mAbandoned);
402                     writer.print(" mReset="); writer.println(mReset);
403         }
404     }
405 }