Pages

Search This Blog

Saturday, 15 December 2012

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.

Loader is discussed at various place but creating your own custom loader is the topic remains to discuss. Let take one case where loader is useful in android

Suppose application download data from network and show inside a list. suddenly user change phone orientation. Data will start downloading again. To avoid this case, Loader are right thing to use

Loader life cycle include three method

public Loader<DataHandler> onCreateLoader(int arg0, Bundle arg1) , called when loader initialize once only

public void onLoadFinished(Loader<DataHandler> arg0, DataHandler arg1) every time when applciation interact with Loader. And return data

Note: Here DataHandler is application custom class

Now this article will include steps and description to create its own custom loader . It had one list fragment. And after download data using AsyncTaskLoader<DataHandler>, we shows data inside List Fragment

1) One fragment activity is base activity that include on list fragment inside main frame layout2) Now create List Fragment and initialize the Loader with Loader manager like getActivity().getSupportLoaderManager().initLoader(10, null, this).

Loader manager has three argument Loader _ID, Bundle data and LoaderManager.LoaderCallbacks<DataHandler>. Now it will force you to override required method of Loader Manager callback

First will be create loader, here we start one Asynchronous Loader to load data.

Loader reset call everytime it interact with loader

Loader loaded then it call this method , return with data everytime once it downloaded

@Overridepublic void onLoadFinished(Loader<DataHandler> arg0, DataHandler arg1) {mlisListView.setAdapter(new DataBinder(getActivity(), arg1.getData()));setListShown(true);}3) Once we downloaded data, we just have traditional way to set it inside List Fragment using BaseAdapter

These above images show how loader maintain life cycle of data when you change your orientation . LoaderManager can return any kind of data. Here i have my custom class DataHolder and i am returning data as DataHolder