匕首的依赖性2

时间:2018-01-07 22:35:28

标签: java android dependency-injection dagger-2 dagger

我遇到了这个例子link。 创建项目后,我遇到了这个错误

Error:(18, 10) error: android.app.Application cannot be provided without an @Inject constructor or from an @Provides-annotated method.
android.app.Application is injected at
com.app.series.dagger.modules.NetworkModule.provideHttpCache(application)
okhttp3.Cache is injected at
com.app.series.dagger.modules.NetworkModule.provideOkhttpClient(cache)
okhttp3.OkHttpClient is injected at
com.app.series.dagger.modules.NetworkModule.provideRetrofit(…, okHttpClient)
retrofit2.Retrofit is injected at
com.app.series.activities.MainActivity.retrofit
com.app.series.activities.MainActivity is injected at
com.app.series.dagger.components.NetComponent.inject(activity)

另外我有一个与DaggerNetComponent相关的错误,它无法解决,但是从在线阅读我认为可能是因为第一个错误

据我所知,它似乎是通过活动而不是应用程序,反之亦然。我试了几个小时才能理解这个问题出在哪里,但是我没有看到它。

这是我目前的代码

AppModule

@Module
public class AppModule
{
    SeriesApplication mApplication;

    public AppModule(SeriesApplication mApplication) {
        this.mApplication = mApplication;
    }

    @Provides
    @Singleton
    SeriesApplication provideApplication() {
        return mApplication;
    }
}

SeriesApplication

public class SeriesApplication extends Application
{
    private NetComponent mNetComponent;

    private static SeriesApplication instance;
    public static SeriesApplication getInstance() {
        return instance;
    }
    public static void setInstance(SeriesApplication instance) {
        SeriesApplication.instance = instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setInstance(this);
        mNetComponent = DaggerNetComponent.builder()
                .appModule(new AppModule(this))
                .netModule(new NetworkModule("http://www.jsonplaceholder.typicode.com/"))
                .build();
    }

    public NetComponent getNetComponent() {
        return mNetComponent;
    }
}

NetComponent

@Singleton
@Component(modules = {AppModule.class, NetworkModule.class})
public interface NetComponent {
    void inject(MainActivity activity);
}

NetworkModule

@Module
public class NetworkModule {
    String mBaseUrl;

    public NetworkModule(String mBaseUrl) {
        this.mBaseUrl = mBaseUrl;
    }

    @Provides
    @Singleton
    Cache provideHttpCache(Application application) {
        int cacheSize = 10 * 1024 * 1024;
        Cache cache = new Cache(application.getCacheDir(), cacheSize);
        return cache;
    }

    @Provides
    @Singleton
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }

    @Provides
    @Singleton
    OkHttpClient provideOkhttpClient(Cache cache) {
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.cache(cache);
        return client.build();
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
    }
}

MainActivity

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((SeriesApplication) getApplication()).getNetComponent().inject(this);



        //Create a retrofit call object
        Call<List<Series>> posts = retrofit.create(Restapi.class).getPosts();

        //Enque the call
        posts.enqueue(new Callback<List<Series>>() {
            @Override
            public void onResponse(Call<List<Series>> call, Response<List<Series>> response) {
                //Set the response to the textview
//                textView.setText(response.body().get(0).getBody());

            }

            @Override
            public void onFailure(Call<List<Series>> call, Throwable t) {
                //Set the error to the textview
//                textView.setText(t.toString());
            }
        });

我的依赖项:

dependencies {
        implementation fileTree(include: ['*.jar'], dir: 'libs')
        implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
        implementation 'com.android.support:design:26.0.0-beta1'
        implementation 'com.android.support.constraint:constraint-layout:1.0.2'
        implementation 'com.android.support:support-v4:26.0.0-beta1'
        implementation 'com.google.android.gms:play-services-plus:11.0.4'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.1'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
        implementation 'com.android.support:cardview-v7:26.0.0-beta1'
        compile 'com.squareup.picasso:picasso:2.5.2'
        compile 'com.google.dagger:dagger:2.11-rc2'
        annotationProcessor 'com.google.dagger:dagger-compiler:2.11-rc2'
        implementation 'com.google.code.gson:gson:2.2.4'
        annotationProcessor 'com.jakewharton:butterknife:5.1.1'
        implementation 'com.jakewharton:butterknife:5.1.1'
        compile 'com.squareup.retrofit2:converter-gson:2.0.1'
        compile 'com.squareup.retrofit2:retrofit:2.1.0'

        //OkHttp
        compile 'com.squareup.okhttp3:okhttp:3.2.0'
        compile 'com.squareup.okio:okio:1.7.0'

    }

我感谢此时的任何帮助,谢谢

2 个答案:

答案 0 :(得分:1)

NetworkModule中,您提供的是Application,而不是SeriesApplication

@Provides
@Singleton
Cache provideHttpCache(Application application) {
    int cacheSize = 10 * 1024 * 1024;
    Cache cache = new Cache(application.getCacheDir(), cacheSize);
    return cache;
}

@Provides
@Singleton
Cache provideHttpCache(SeriesApplication application) {
    int cacheSize = 10 * 1024 * 1024;
    Cache cache = new Cache(application.getCacheDir(), cacheSize);
    return cache;
}

答案 1 :(得分:1)

使用以下代码:

template <typename T1, typename T2> 
tree<T1,T2>::tree(int numNodes, T2& rData)
{
  auto iter = hierarchy.begin();
  auto count = 0;
  for(; count < numNodes; ++iter, ++count)
  {
    *iter = make_unique<node<T1>>(rData[count]);
  }
  auto iter = hierarchy.begin();
  lnkNodes(iter);
}

你告诉匕首,“每当我要求你提供 @Provides @Singleton Cache provideHttpCache(Application application) { ... } 时,请使用Cache来构建Application

但是你没有说明匕首应该如何获得Cache的实例。 以下provider方法返回一个完全其他的对象:

Application

它返回 @Provides @Singleton SeriesApplication provideApplication() { return mApplication; } 的实例。 而是将返回类型更改为SeriesApplication

Application

现在匕首不会混淆。