Search code examples
androidsqliteandroid-loadermanagerandroid-cursorloaderasynctaskloader

Must an activity or fragment have a separate loader for type of each database operation performed?


Seems the Google-recommended way (using the android support library) for a fragment or activity to interact with a sqlite database is via a loader that extends AsyncTaskLoader and works similar to the way CursorLoader does for ContentProviders.

A single activity or fragment may interact with a database in a variety of ways, updating, deleting, and querying data in one or more tables. But since a loader has only one place in which to carry out database manipulation (i.e. in loadInBackground()), is the developer expected to write a separate loader for each type of interaction, especially since it seems the only way to parametrize the behavior in loadInBackground() is by passing arguments to the loader's constructor via the args argument to LoaderManager.initLoader()?

Thanks much.


Solution

  • When not using a ContentProvider, i.e. when using sqlite directly, use AsyncTaskLoader if the set of database operations to be performed returns a Cursor. The set may include any kind of operation - update, query, delete, insert. These operations should be executed in AsyncTaskLoader.loadInBackground().

    If the set of database operations does not result in a Cursor being returned, use an AsyncTask. In this case, the operations should be executed in AsyncTask.doInBackground().