android getting NULL error on inject DI into class

2019-03-07 00:31发布

问题:

I can make DI from some class to use in application such as Retrofit, Picasso. they can work fine when i use them on Activity but when i try to use some DI on other class i get NULL, for exmple this code work fine

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

for GithubService i get created instance successfull, not i'm trying to use that into GetLatestRepositories, but i get NULL, how can i define correctly that to injecting into 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 component 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();
}

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

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

回答1:

Before you can even use the object from GithubService class you need to do the following:

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

In your case you will have to do something like:

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

Now you can use the githubService object:

repositoryCall = githubService.getAllRepositories();

This is a type of design pattern called creational.