Search code examples
androidandroid-sqliteandroid-loadermanagerandroid-loader

How to do mulitple serial DB queries with CursorLoader


I want to make 2 queries to the DB using CursorLoader, with a specific order before displaying data to the screen. More specifically I want to execute the 2nd query only after the 1st query has returned its data.

What I do know is:

  1. I execute the 1st query mLoaderManager.initLoader(TASK_LOADER_1, null, this);

  2. I get the result in onLoadFinished(Loader<Cursor> loader, Cursor data), and from there I create a new Loader mLoaderManager.initLoader(TASK_LOADER_2, null, this); which executes the 2nd query

  3. When the 2nd query returns I display the data.

Is there a more efficient way to do this using Loaders? What if I wanted to do more queries in a row? Should I follow the same pattern?

Thank you.


Solution

  • Yes, from my opinion the implementation is okay. While initiating a loader using the initLoader function, you are specifying an id that is associated with the loader and you can trace back which loader callback is finished fetching data from the database in your onLoadFinish method matching the same loader.getId() method.

    In case of sequential database call (if this is your exact use case), you need to call the next database call when the previous one finished executing like the way you are doing it now.

    For a series of multiple sequential database calls, you may following the same structure. Just maintain a queue to keep track of the subsequent database calls.