When should I do certain SQLite operations on another thread(not the main thread)? When should I do certain SQLite operations on another thread(not the main thread)? sqlite sqlite

When should I do certain SQLite operations on another thread(not the main thread)?


General rule for everything: If it's fast enough, do it on the main thread. If not, use a worker thread.

Unless you have a ridiculously huge database, a single operation almost never warrants a separate thread. Databases in general are designed to scale well, but of course a very big database (10,000+ rows?) will be a bit slower than a small one. 30 rows, however, is nothing.

I would start threading stuff if you have a lot of operations going on, like a bunch of queries, or complicated queries that span several tables.

As with everything - profile your app, and if it's too slow, optimize. Don't write an awesome synchronized super-duper multi-core-ready database handler if none of your queries takes longer than 2ms.


Always measure before you optimize!

Make sure that DB operations you do affect user experience and than start looking for a solution.

If database stuff gets slow, then use AsyncTask, which was designed to perform tasks in the background, and then update the GUI on EDT.


There is absoulutely not reason to use a thread here. Just return the cursor, extract the information from the cursor and return it to the main activity.

Specifically speaking a thread is something ideally that is going to repeat until something happens or it times out. Since the database you are using i'm assuming is on the phone, it would take practically zero time to access it.

Also another thing you can do is create a Utility class to assist with your activity to database interaction. It would be what your activity calls to interact with the database. Specifically the flow of control would be like this:

Activity -> Utility -> Database

Its between the activity and the database to keep them isolated from each other and make it much easier to access whatever it needs since it doesn't have to go directly to the database itself.