没有注射成员。你想添加一个注射构造函数吗?

时间:2014-11-22 23:19:03

标签: android dependency-injection dagger

我有这两个简单的模块模块:

的AppModule

@Module(injects =
        {
                HomeActivity.class,
        },
        includes = {
                GoogleApiModule.class,
                DbModule.class,
                GcmModule.class,
        })
public class AppModule {

    private final Application app;

    public AppModule(Application app) {
        this.app = app;
    }

    @Provides
    @Singleton
    Application provideApplication() {
        return app;
    }
}

ApiModule

@Module(injects =
        {                
                LoginFragment.class,
        }, addsTo = AppModule.class)
public class ApiModule {

    private final Context context;

    public ApiModule(Context context) {
        this.context = context;
    }

    @Provides
    @Singleton
    Publicapi providePublicApi() {
        Publicapi.Builder builder = new 
        return new Publicapi();
    }    
}

由于@Inject PublicApi编译器抱怨中的LoginFragment

No injectable members on myapp.publicapi.Publicapi. Do you want to add an injectable constructor? required by myapp.fragments.LoginFragment for myapp.modules.AppModule

我一直在读几个主题,我确信我做得对,显然是错的。这个设置有什么问题?

1 个答案:

答案 0 :(得分:0)

Publicapi必须有一个接收上下文的构造函数方法,并且必须为其分配一个上下文类属性。我的意思是:

public Publicapi(Context context) {
    this.context = context;
}

然后......在ApiModule中,您必须实例化将上下文作为参数发送的构造函数。这样的事情:

// (With "a" in lower case like the class name) !!!
@Provides
@Singleton
Publicapi providesPublicapi(Context context) { 
   return new Publicapi(context);
} 

问候!