在我的Android应用中,我试图将一个DatabaseHelper对象注入到ArticleView中,但Dagger抱怨时出现以下错误消息:
Error:(11, 7) error: android.content.Context cannot be provided without an @Provides-annotated method.
dk.jener.paperflip.ArticleActivity.database
[injected field of type: dk.jener.paperflip.model.retriever.DatabaseHelper database]
dk.jener.paperflip.model.retriever.DatabaseHelper.<init>(android.content.Context context)
[parameter: android.content.Context context]
我该如何解决?
我的代码如下:
@Singleton
@Module
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
@Inject
public DatabaseHelper(Context context) {
super(context, "foobar", null, 1);
}
...
}
@Module
public class ApplicationContextModule {
private final Context context;
public ApplicationContextModule(Context context) {
this.context = context;
}
@Provides
@Singleton
public Context provideApplicationContext() {
return context;
}
}
@Singleton
@Component(modules = { DatabaseHelper.class })
public interface RetrieverComponent {
void inject(ArticleActivity activity);
}
public class ArticleActivity extends AppCompatActivity {
@Inject
DatabaseHelper database;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
RetrieverComponent component = DaggerRetrieverComponent.builder()
.applicationContextModule(new ApplicationContextModule(getApplicationContext()))
.build();
component.inject(this);
}
...
}
据我所知,Context已由ApplicationContextModule#provideApplicationContext提供。
答案 0 :(得分:0)
在提供的代码中,您似乎错过了在组件中包含ApplicationContextModule
模块。应该是这样的:
@Component(modules = { ApplicationContextModule.class })
同样DatabaseHelper
不需要@Module
注释(它不是模块,只是普通类)。