문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top