【问题标题】:android getting NULL error on inject DI into classandroid在将DI注入类时出现NULL错误
【发布时间】:2017-04-09 15:38:52
【问题描述】:

我可以将某个类的 DI 用于应用程序,例如 RetrofitPicasso。 当我在 Activity 上使用它们时它们可以正常工作,但是当我尝试在其他类上使用一些 DI 时,我得到 NULL,例如这段代码可以正常工作

public class ActivityRegister extends BaseActivities {

    @Inject
    GithubService githubService;

    @Inject
    JobManager jobManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        ...
        repositoryCall = githubService.getAllRepositories();
        ...
}

private void getRepositories() {
    repositoryCall.enqueue(new Callback<List<GithubRepo>>() {
        @Override
        public void onResponse(Call<List<GithubRepo>> call, Response<List<GithubRepo>> response) {
            List<GithubRepo> repoList = new ArrayList<>();
            repoList.addAll(response.body());
            Log.e("JOB ", "OK");
        }

        @Override
        public void onFailure(Call<List<GithubRepo>> call, Throwable t) {
            Log.e("JOB ", "NO!!");
        }
    });
}

对于GithubService,我成功创建了实例,而不是我试图将其用于GetLatestRepositories,但我得到NULL,如何正确定义注入类?

public class GetLatestRepositories extends Job {
    @Inject
    GithubService githubService;

    private Call<List<GithubRepo>> repositoryCall;

    public GetLatestRepositories() {
        super(new Params(Priority.MID).requireNetwork().persist());
        repositoryCall = githubService.getAllRepositories();
    }

    @Override
    public void onAdded() {

    }

    @Override
    public void onRun() throws Throwable {
        repositoryCall.enqueue(new Callback<List<GithubRepo>>() {
            @Override
            public void onResponse(Call<List<GithubRepo>> call, Response<List<GithubRepo>> response) {
                List<GithubRepo> repoList = new ArrayList<>();
                repoList.addAll(response.body());
                Log.e("JOB ", "OK");
            }
            @Override
            public void onFailure(Call<List<GithubRepo>> call, Throwable t) {
                Log.e("JOB ", "NO!!");
            }
        });
    }
    @Override
    protected void onCancel(int cancelReason, @Nullable Throwable throwable) {

    }

    @Override
    protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {
        return null;
    }
}

ActivityRegisterComponent组件类:

@ActivityRegisterScope
@Component(modules = ActivityRegisterModule.class, dependencies = GithubApplicationComponent.class)
public interface ActivityRegisterComponent {

    void injectActivityRegister(ActivityRegister homeActivity);
}

GithubApplicationComponent:

@GithubApplicationScope
@Component(modules = {GithubServiceModule.class, PicassoModule.class, JobManagerModule.class, ActivityModule.class})
public interface GithubApplicationComponent {

    Picasso getPicasso();

    GithubService getGithubService();

    JobManager getJobManager();
}

应用类:

public class Alachiq extends Application {

    ...
    public static  Alachiq                    alachiq;
    public static  String                     packageName;
    public static  Resources                  resources;

    private static Context                    context;

    private        GithubService              githubService;
    private        Picasso                    picasso;
    private        GithubApplicationComponent component;
    private        JobManager                 jobManager;
    private static Alachiq                    instance;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //@formatter:off
            resources   = this.getResources();
            context     = getApplicationContext();
            packageName = getPackageName();
        //@formatter:on


        Timber.plant(new Timber.DebugTree());

        component = DaggerGithubApplicationComponent.builder()
                .contextModule(new ContextModule(this))
                .build();

        githubService = component.getGithubService();
        picasso = component.getPicasso();
        jobManager = component.getJobManager();
    }

    public GithubApplicationComponent component() {
        return component;
    }

    public static Alachiq get(Activity activity) {
        return (Alachiq) activity.getApplication();
    }

    public static Alachiq getInstance() {
        return instance;
    }

    public static Context getContext() {
        return context;
    }
}

和 ActivityRegister onCreate:

ApplicationComponent component = DaggerApplicationComponent.builder()
                .githubApplicationComponent(Alachiq.get(this).component())
                .build();

GithubService类:

public interface GithubService {

    @GET("users/{username}/repos")
    Call<List<GithubRepo>> getReposForUser(@Path("username") String username);

    @GET("repositories")
    Call<List<GithubRepo>> getAllRepositories();

    @GET("users/{username}")
    Call<GithubUser> getUser(@Path("username") String username);
}

【问题讨论】:

  • 你是否暗示你在这一行得到空指针:“repositoryCall = githubService.getAllRepositories();” ?
  • 你在哪里调用注入?活动和服务由 Android 框架创建,因此需要手动注入。
  • @ScottS 是的,先生,我在此文件中为 githubService 得到空值 GetLatestRepositories
  • @GabeSechan 我将GetLatestRepositories 类中的注入称为@Inject GithubService githubService;
  • 这不是调用注入。对于框架创建的项目(活动、服务、视图等),您必须在您实例化的控制器上调用注入函数,并将服务/活动/视图作为参数传入

标签: android dagger-2


【解决方案1】:

在您甚至可以使用 GithubService 类中的对象之前,您需要执行以下操作:

 myComponent= DaggerMyComponent.builder().computerModule(new ComputerModule()).build();//replace accordingly.

在您的情况下,您将不得不执行以下操作:

githubService = DaggerGithubApplicationComponent.builder().nameofYourModule(new NameOfTheClass()).build);

现在你可以使用 githubService 对象了:

repositoryCall = githubService.getAllRepositories();

这是一种称为创造的设计模式。

【讨论】:

  • GetLatestRepositories类中使用githubService = GithubApplicationComponent.builder().nameofYourModule(new NameOfTheClass()).build);
  • 我将GithubService 类粘贴到我的帖子中
  • 不,在你的应用程序类中。
  • 它必须在您的应用程序类中。在 onCreate() 中
  • 它的DaggerGithubApplicationComponent,看来你的意思是不正确的,因为我得到错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
相关资源
最近更新 更多