android 将 DI 注入 class 时出现 NULL 错误

android getting NULL error on inject DI into class

我可以从一些 class 制作 DI 以用于 RetrofitPicasso 等应用程序。 当我在 Activity 上使用它们时它们可以正常工作但是当我尝试在其他 class 上使用一些 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,我如何正确定义注入到class?

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分量class:

@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();
}

申请class:

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;
    }
}

和Activity注册onCreate:

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

GithubService class:

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);
}

在您甚至可以使用来自 GithubService 的对象之前 class 您需要执行以下操作:

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

在您的情况下,您必须执行以下操作:

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

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

repositoryCall = githubService.getAllRepositories();

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