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
.
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
Simple Solution
1 Move your logic from
onCreate
toattachBaseContext
in your Application.2 You can now
inject
inOnCreate
in your ContentProvider:Disclaimer: Full Credits to @LeEnot from this russian blog: Dagger2 Inject in Content Provider. The answer is listed here for convenience as it is not available in English.
based on @Mick answer and @LeEnot article I posted an article on Medium using new Dagger 2 features.
https://medium.com/@pedro.henrique.okawa/content-providers-dependency-injection-dagger-2-4ee3e49777b
But basically I put the Dagger-Android dependency:
Implemented my custom Application class with HasContentProviderInjector interface and changed to inject my dependencies on attachBaseContext:
And injected my databaseHelper instance on my ContentProvider class:
PS: I decided to not use DaggerContentProvider class because most of us may already have a base class for some Android components.
I hope it help you and thanks again to @Mick and @LeEnot
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:
Apparently this suggestion cannot be disregarded. Implementing the onCreate() method provides an example using an SQLiteOpenHelper with a content provider.
As Alex Baker pointed out, the solution of the issue is to defer the injection when an operation (query, insert, update, delete) is called for the first time.
to make an example:
This won't work:
}
but this will work correctly:
}