Speeding Up Databases with Asynchronous Tasks

You may have noticed that there is a “strict mode policy violation error” message in the LogCat view when the database is first created. This is caused by the code accessing the database in the main UI thread. Because database access can be slow, you want to try to avoid any database access on the main UI thread.

One solution is to have database operations run in another thread by using the AsyncTask class. Sometimes database operations must happen in a certain order or must be wrapped in a transaction, so it’s not always easy to run the operations asynchronously. Follow these steps.

1. Open SQLiteHelper, and add a private static variable to keep track of the number of asynchronous database calls ...

Get Learning Android™ Application Programming: A Hands-On Guide to Building Android Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.