Search code examples
androidandroid-contentprovidersqliteopenhelper

Best practice for using a single SQLiteOpenHelper for use by many ContentProviders


In my app (a SyncAdapter) I include many ContentProviders for use by other apps and was wondering whether it is appropriate to attempt to share a single SQLiteOpenHelper instance between them all to use? If so, how?

If that's not appropriate, is it considered correct to (as examples seem to indicate) repeat instantiation of the SQLiteOpenHelper within each ContentProvider's onCreate method; seems like there should be a better way!

Is there sufficient information in the Manifest for the Operating System to instantiate ContentProviders without creating their containing Application first? If so, then I can not hold a static SQLiteOpenHelper in a class that extends Application for retrieval by ContentProviders.

Help!


Solution

  • The answer was to merge my ContentProviders into a single ContentProvider that is wired-up to handle my various URIs/tables; here's an example from Google themselves. This way you can instantiate your SQLiteOpenHelper and set it to a field for your overridden methods to use, again, see the example. By the way, another good (in the interests of best practice) pattern I picked up from that code is to: override applyBatch to wrap everything it does in a transaction. Thereafter use it and only it (via. ContentProviderOperations) whenever you want to do any persistence; if you do this you can omit transactions from your actual overridden update, delete and insert methods - because you'll not be using them directly! The latter appeals to me as it simplifies my insert, update and delete methods and ensures that a whole sequence of related changes can be rolled back easily if an Exception is thrown.