Loader is good choice for prevent memory leak if you want to load data in background when oncreate method is called. For example when we execute Asynctask in oncreate method and we rotate the screen so the activity will recreate which will execute another AsyncTask again, so probably two Asyntask running in parallel together rather than like loader which will continue the background process we executed before.
|LoaderManager||An abstract class associated with an Activity or Fragment for managing one or more Loader instances.|
|LoaderManager.LoaderCallbacks||A callback interface for a client to interact with the LoaderManager.|
|Loader||An abstract class that performs asynchronous loading of data.|
|AsyncTaskLoader||Abstract loader that provides an AsyncTask to do the work.|
|CursorLoader||A subclass of AsyncTaskLoader that queries the ContentResolver and returns a Cursor.|
Introduced in Android 3.0, loaders make it easy to asynchronously load data in an activity or fragment. Loaders have these characteristics:
- They are available to every Activity and Fragment.
- They provide asynchronous loading of data.
- They monitor the source of their data and deliver new results when the content changes.
- They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.
When not to use LoadersYou shouldn’t use Loaders if you need the background tasks to complete. Android destroys Loaders together with the Activities/Fragments they belong to. If you want to do some tasks, that have to run until completion, do not use Loaders. You should use services for this kind of stuff instead.
AsyncTaskLoader with cache
It's a good practice to cache loaded result to avoid multiple loading of same data.
To invalidate cache
onContentChanged() should be called. If loader has been already started,
forceLoad() will be called, otherwise (if loader in stopped state) loader will be able to understand content change with
onContentChanged() must be called from the process's main thread.
Javadocs says about takeContentChanged():
Take the current flag indicating whether the loader's content had changed while it was stopped. If it had, true is returned and the flag is cleared.
AsyncTaskLoader is an abstract
Loader that provides an
AsyncTask to do the work.
Here some basic implementation:
Loader is initialized within the activity's
onCreate() method, or within the fragment's
onActivityCreated(). Also usually activity or fragment implements
In this example, when loader completed, toast with result will be shown.
Pass parameters using a Bundle
You can pass parameters by Bundle:
Get the value in onCreateLoader:
To invalidate your old data and restart existing loader you can use