2
在我的Android應用程序,我試圖讓注入ArticleView一個DatabaseHelper對象,但匕首以下錯誤消息抱怨:匕首2俯瞰提供方法
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);
}
...
}
至於我可以計算上下文已經被ApplicationContextModule#provideApplicationContext提供。
現在這是固定的,我得到「databaseHelper必須設置」。 – Jenrik
也許最好用當前的代碼發佈另一個問題(不要編輯當前的答案) – Ognyan