使用Dagger 2无法将数据注入Fragment

时间:2017-06-27 20:32:56

标签: android dagger-2

我在ApplicationModule中创建了数据,我想将其注入片段中,然后得到:

Data cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method

以下是我的示例代码:

@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {

    BaseApplication baseApplication();
    Data data();

}

ApplicationModule:

@Module
public class ApplicationModule {

    private final BaseApplication mApplication;

    public ApplicationModule(BaseApplication application) {
        mApplication = application;
    }

    @Provides
    @Singleton
    BaseApplication provideBaseApplication() {
        return mApplication;
    }

    @Provides
    @Singleton
    Data provideData() {
        return new Data("sample data");
    }

}

接下来是活动组件:

@PerActivity
@Component(dependencies = ApplicationComponent.class,
        modules = {
                ActivityModule.class
        }
)
public interface ActivityComponent {

    void inject(MainActivity activity);

}

活动模块:

@Module
public class ActivityModule {

    private AppCompatActivity mActivity;

    public ActivityModule(AppCompatActivity activity) {
        this.mActivity = activity;
    }

}

接下来是片段组件:

@PerFragment
@Component(dependencies = ActivityComponent.class, modules = FragmentModule.class)
public interface FragmentComponent {

    void inject(MainFragment fragment);

}

最后片段模块:

@Module
public class FragmentModule {

    private final MainFragment mFragment;

    public FragmentModule(MainFragment fragment) {
        this.mFragment = fragment;
    }

}

我将数据注入Fragment并得到错误。

现在我不明白为什么我会收到错误。请帮助我,因为我在互联网上查看了示例代码,但我不知道我的代码有什么问题。

0 个答案:

没有答案