Short version: what is the best practice way to access the same DB from both activity and from started service?
Long version: I have a case where I start persistent service from activity. Service is populating the DB with data while activity is displaying it on screen. Neither of them is running all the time - service can run when there is no activity, and activity can run when service is not started yet. But service can only be stopped from activity (it never stops itself).
I am using subclass of SQLiteOpenHelper to access the DB. The problem I tripped over is that apparently closing DB in one SQLiteOpenHelper
instance closes it in another too.
I can think of these options:
- singleton pattern (single
SQLiteDatabase
instance in a public static var - only activity can close it (because it knows if the service is running or not)) - ugly - check if service/activity is running before closing it in the other one - ugly
- build acquire/release into SQLiteOpenHelper's
getReadableDatabase()
/close()
I would go with 3., but this must be a very common pattern, so I'm wondering if there is such a built-in mechanism in place already - I'd hate to reinvent the wheel.
In other words, what would be the proper way to do it?