-1

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!

fr1550n
  • 1,055
  • 12
  • 23
  • why do you need many contentproviders to access 1 database? (Application is always created first and always exists in activities, services, broadcast receivers and content provider) – njzk2 Jun 04 '13 at 18:57
  • Broadly speaking I have a ContentProvider per Table in the Database. How do you know that android first creates the Application? – fr1550n Jun 04 '13 at 19:01
  • because that's what the documentation for the application class says. – njzk2 Jun 04 '13 at 20:30
  • http://developer.android.com/reference/android/app/Application.html#onCreate() states: "Called when the application is starting, before any activity, service, or receiver objects **(excluding content providers)** have been created." This bothers me, perhaps it's just worded in an ambiguous way? – fr1550n Jun 04 '13 at 20:44
  • So, I guess one answer is to stuff everything into one GIGANTIC ContentProvider to rule them all, like google do here: https://code.google.com/p/iosched/source/browse/android/src/com/google/android/apps/iosched/provider/ScheduleProvider.java funnily enough, this does not appeal to me! – fr1550n Jun 04 '13 at 23:02
  • that would work. the first part of the path pretty much designates the table. – njzk2 Jun 05 '13 at 07:27

1 Answers1

0

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.

fr1550n
  • 1,055
  • 12
  • 23