Search code examples
androidandroid-sqliteandroid-cursorandroid-cursorloader

What's practical purpose of cursorLoader?


I saw some articles about CursorLoader like this, but I still don't understand the particular purpose of using it.

I developed apps with SQL and cursor retrieving. The point is it was very fast. I queried and parsed cursor with >500 record and 8 columns by a few millisecond. So didn't notice any delay event on old phones. So why do I need to use it?


Solution

  • A CursorLoader is used ostensibly to query a ContentProvider with LoaderManager.LoaderCallbacks<Cursor>.

    There are two things that you need to keep in mind for understanding the CursorLoader:

    • It loads data on a separate thread.

    • It monitors the underlying data source for updates, re-querying when changes are detected.

    Now coming to the LoaderManager. Simply stated, the LoaderManager is responsible for managing one or more Loaders associated with an Activity or Fragment. Each Activity and each Fragment has exactly one LoaderManager instance that is in charge of starting, stopping, retaining, restarting, and destroying its Loaders. These events are sometimes initiated directly by the client, by calling initLoader(), restartLoader(), or destroyLoader(). Just as often, however, these events are triggered by major Activity/Fragment lifecycle events. For example, when an Activity is destroyed, the Activity instructs its LoaderManager to destroy and close its Loaders (as well as any resources associated with them, such as a Cursor).

    The LoaderManager does not know how data is loaded, nor does it need to. Rather, the LoaderManager instructs its Loaders when to start/stop/reset their load, retaining their state across configuration changes and providing a simple interface for delivering results back to the client.

    So you see, all this is not easily possible when you use a simple AsyncTask and query an SQLite database. This is why the framework provides CursorLoader and LoaderManager:

    • To perform queries on a separate thread.
    • To monitor the data source for changes and update the UI.
    • To integrate easily with the life cycle of Activity and Fragment.