【问题标题】:Dagger injected class keeps being null with DaggerDagger 注入的类在使用 Dagger 时一直为空
【发布时间】:2020-01-25 19:08:54
【问题描述】:

我正在尝试将CacheManager 的实例注入GetTodoRepository,Dagger 可能会成功执行此操作,因为我没有收到任何与匕首相关的错误。但是当在GetTodoRepository 中使用cacheManager 时,我得到一个 NullPointerException

public class GetTodoRepository {

    @Inject
    public CacheManager cacheManager;

    public RetrofitService retrofitService;
    private ResultListener listener;

    public GetTodoRepository(@NonNull ResultListener listener) {
        this.retrofitService = new RetrofitService();
        this.listener = listener;
    }
}

@Module
public class AppModule {

    private Application application;

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

    @Provides
    @Singleton
    public Context providesApplicationContext() {
        return application.getApplicationContext();
    }

    @Provides
    @Singleton
    public CacheManager provideCacheManager(Context Context) {
        return new CacheManager(Context);
    }

}



@Singleton
@Component(modules = AppModule.class)
public interface TodoComponents {
    void inject(MainViewModel mainViewModel);
    void inject(CacheManager cacheManager);
    void inject(GetTodoRepository getTodoRepository);
    void inject(PostTodoRepository postTodoRepository);
}

【问题讨论】:

  • 你的组件是什么样的?
  • @Md.Asaduzzaman 组件类现在在问题中可见
  • 你必须 注入 GetTodoRepository 才能匕首。你这样做了吗?
  • @Md.Asaduzzaman 我只做了我粘贴的内容。注入匕首是什么意思?

标签: java android dagger-2 dagger


【解决方案1】:

1)在Application类中设置Dagger(组件)

public class TodoApplication extends Application {

private static AppComponent components;

@Override
public void onCreate() {
    super.onCreate();
    components = DaggerAppComponent.builder()
            .appModule(new AppModule(this))
            .build();
}


public static AppComponent getAppComponent() {
    return components;
}

}

2)从注入目标类中的Application类调用Component对象

public GetTodoRepository(@NonNull ResultListener listener) {
    this.listener = listener;
    TodoApplication.getAppComponent().inject(this);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多