[英]Null Pointer Exception in Constructor Injection Dagger2 Android
我試圖在我的Interactor類中注入上下文,這給了我一個空指針異常。 我已經使用了MVP模式,並且試圖在非活動類中訪問上下文。 我不確定這是否是最好的技術。
模塊:
@Module
public class ContextModule {
private final Context context;
public ContextModule(Context context) {
this.context = context;
}
@Singleton
@Provides
public Context getContext() {
return this.context;
}
}
零件:
@Singleton
@Component(modules = {ContextModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
}
應用程式
public class App extends Application {
private AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.builder()
.contextModule(new ContextModule(this))
.build();
}
public AppComponent getAppComponent() {
return appComponent;
}
}
主要活動
public class MainActivity extends AppCompatActivity implements
TaskContract.IMainView {
@Inject
MainInteractor mainInteractor;
private MainPresnter mainPresnter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((App) getApplication()).getAppComponent().inject(this);
mainPresnter = new MainPresnter(this);
}
@Override
public void getRandomNumber(int rNum) {
Toast.makeText(this, "" + rNum, Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
super.onResume();
mainPresnter.fetchFromService();
}
}
主持人
public class MainPresnter implements TaskContract.IMainPresenter,
TaskContract.OnTaskCompletionResult {
private TaskContract.IMainView mainView;
private MainInteractor mainInteractor;
public MainPresnter(TaskContract.IMainView mainView) {
this.mainView = mainView;
mainInteractor = new MainInteractor(this);
}
@Override
public void fetchFromService() {
mainInteractor.callService();
}
@Override
public void onSuccess(int rNum) {
mainView.getRandomNumber(rNum);
}
}
互動者
public class MainInteractor implements TaskContract.IMainInteractor {
private static final int JOB_ID = 100 ;
private Context context;
@Inject
public MainInteractor(Context context) {
this.context = context;
}
public MainInteractor(TaskContract.OnTaskCompletionResult completionListener)
{
TaskService.setCompletionListener(completionListener);
}
@Override
public void callService() {
JobInfo jobInfo = new JobInfo.Builder(JOB_ID,
new ComponentName(context, TaskService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPeriodic(10000)
.build();
JobScheduler jobScheduler = (JobScheduler)
context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(jobInfo);
}
}
搖籃
implementation 'com.google.dagger:dagger-android:2.11'
annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
您無需在Presenter中注入Interactor-因此它將沒有上下文。
您可能需要重組Presenter以將Interactor作為依賴項-這也意味着您需要重組完成偵聽器的設置方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.