Android SQLite Query, Insert, Update, Delete, Always Need to be On Background Thread?

AutoM8R picture AutoM8R · Mar 12, 2014 · Viewed 11.8k times · Source

I currently use Loaders to grab data from my ContentProvider (to enable auto-updating of my Cursors). This approach is straight-forward for Querying the database, though, it seems ill suited for any other DB operation (such as Insert, Update, Delete).

My questions are:

  1. Do all SQLite operations need to be on a background thread, or is it safe to do simple operations like Inserting, Updating, or Deleting a single row on the UI thread?
  2. What is a nice design patter to ensure all queries go through a background thread? I would like to implement AsyncTask, should I create a SuperTask so to speak that extends AsyncTask and Executes each SQLite operation? (Bonus: Can you provide bare-bones example?)

Answer

user695992 picture user695992 · Mar 12, 2014

I have done SQLite operations on my UI Thread. I guess the question really becomes whether your queries will ever take a long time or not. I've never had my application crash from taking too long to execute SQL calls on my SQLite database.

With that said, if you plan on writing complex queries that can take time to load you would want to run it as an AsyncTask or Thread and use callbacks to update your UI if need be.

This is a great tutorial on SQLite on Android (It also addresses some of the complex sql timing issues you were talking about): http://www.vogella.com/tutorials/AndroidSQLite/article.html