Android: Simple Loader and LoaderManager for loading data example

    Loader is useful while maintaining life cycle of activity and avoiding performing big task again and again. Loader provide a way to keep old data while changing orientation. Every loader has its own unique ID and its created only once. Next time it will use the previous instance.
    For managing one or more Loader(s) we use LoaderManager. It has LoaderCallback<D> interface and we must implements it in Activity (our Activity must extends FragmentActivity).

LoaderManager.LoaderCallBack<D> life cycle include three method
onCreateLoader(): called when loader initialize once only.
onLoadFinished(): every time when applciation interact with Loader. And return data.
onLoaderReset(): Called when a previously created loader is being reset, and thus making its data unavailable.
Okey, now start Eclipse - start a new android project to coding this example.

1. Create a simple model ( for each element of ListView:
2. We create and load data by custom a AsyncTaskLoader, it source code is simple like this:
3. In LoadActivity (to run):
- Extend it from FragmentActivity.
- Declare it implements LoaderManager.LoaderCallback<List<Friend>>.
- Override all necessary methods.
- Initialize and active LoaderManger instance through initLoader() method.
- In onCreateLoader() method, create a new CustomAsyncTaskLoader instance and invoke it by forceLoad().
Source code:
And this is activity_load.xml:
4. Define a ListView Adapter based on ArrayAdapter to use ListView:
5. Build and run program, we have our result: :D
pic name pic name


Previous post
« Prev Post
Next post
Next Post »