I searched, but couldn't find any concrete answer to this question; so here goes.
I know that I shouldn't access the database from the UI thread. Also, the AsyncTask isn't good for longer time tasks(memory leaks etc.). So I'm guessing I should make use of a service.
Should I open the SqliteOpenHelper as a service in a new Thread? Do you have any example code of how to do this?
Is the SQLiteOpenHelper automatically run in another thread by Android? I didn't find any example code online that didn't run the SQLiteOpenHelper on the UI thread. Why is this?
Thanks!
Is the SQLiteOpenHelper automatically run in another thread by Android?
In Java, objects are not run on threads. Methods are called on threads.
I am not aware of any SQLiteOpenHelper
method that automatically uses its own thread — thread management is the responsibility of the objects that call methods on the SQLiteOpenHelper
.
I didn't find any example code online that didn't run the SQLiteOpenHelper on the UI thread
In Java, objects are not run on threads. Methods are called on threads.
Here is a sample app that calls methods like getReadableDatabase()
on a SQLiteOpenHelper
from a background thread. Here is another such sample app. Here is yet another sample app. The first two use AsyncTask
; the latter one uses a regular Thread
with an event bus.
Should I open the SqliteOpenHelper as a service in a new Thread?
A SQLiteOpenHelper
cannot be a Service
, as Java does not support multiple inheritance, and both SQLiteOpenHelper
and Service
are concrete classes.
You are certainly welcome to use an instance of SQLiteOpenHelper
from inside a Service
, if you wish.
Also, the AsyncTask isn't good for longer time tasks(memory leaks etc.).
Proper use of an AsyncTask
will not trigger a memory leak (e.g., manage it by a retained fragment). The decision of whether to use an AsyncTask
versus something else (e.g., an ordinary thread, IntentService
) is more based on how long the work will take and what the risks are of your process being terminated before that work completes.