Search code examples
androiddagger

Inject database in a ContentProvider with dagger


I want to inject a singleton SqliteOpenHelper in a ContentProvider. However, it seems that the ContentProvider instance is being built before the Application instance is being created (getApplicationContext() returns null). When can I inject the database? I've tried in the constructor and in the onCreate() method of the ContentProvider.


Solution

  • I faced the same issue and had to defer injection until the database was needed. You might be able to use Dagger's lazy injection to achieve the same effect.

    From the content provider's onCreate documentation:

    You should defer nontrivial initialization (such as opening, upgrading, and scanning databases) until the content provider is used

    Apparently this suggestion cannot be disregarded. Implementing the onCreate() method provides an example using an SQLiteOpenHelper with a content provider.