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

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


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


  1. All SQLite operations do not need to be on a background, but should be. Even simple row updates can impact the UI thread and therefore application responsiveness.

  2. Android includes the AsyncQueryHandler abstract class:

    A helper class to help make handling asynchronous ContentResolver queries easier.

Here are two example implementations from Using AsyncQueryHandler to Access Content Providers Asynchronously in Android. A member class:

class MyQueryHandler extends AsyncQueryHandler {    public MyQueryHandler(ContentResolver cr) {        super(cr);    }    @Override    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {        // query() completed    }    @Override    protected void onInsertComplete(int token, Object cookie, Uri uri) {        // insert() completed    }    @Override    protected void onUpdateComplete(int token, Object cookie, int result) {        // update() completed    }    @Override    protected void onDeleteComplete(int token, Object cookie, int result) {        // delete() completed    }}

An anonymous class:

AsyncQueryHandler queryHandler = new AsyncQueryHandler(getContentResolver()) {    @Override    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {        if (cursor == null) {            // Some providers return null if an error occurs whereas others throw an exception        }        else if (cursor.getCount() < 1) {            // No matches found        }        else {            while (cursor.moveToNext()) {                // Use cursor            }        }    }};

Further details:

  1. Implementing AsyncQueryHandler

  2. http://www.trustydroid.com/blog/2014/10/07/using-asyncqueryhandler-with-content-provider/