Question

How do you access a SQLiteDatabase database in a separate thread (ie: an AsyncTask) of an Activity and make sure that you always leave it in a legal state?

If I understand correctly, the thread can be killed at any moment and the database might remain open, potentially giving an IllegalStateException (SQLiteDatabase created and never closed) at a latter time.

How do you deal with this?

Was it helpful?

Solution

If your AsyncTask is managed by your Activity, then Activity may cancel AsyncTask in proper time (when it becomes vulnerable to be killed by OS, e.g. after Activity.onPause()) so AsyncTask.onCancelled() will be called where you may close the DB.

If your AsyncTask (or a Thread) is not managed by your Activity then your are in trouble and should consider redesigning your architecture.

OTHER TIPS

Two ways:

  1. You can register a Runtime.addShutdownHook(..) and close database there.

  2. Create custom Application and implement onLowMemory() where you close the database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top