细节

使用UseContex类的'printToast()'方法时UseContex类的Null指针异常。UseContex类扩展了mainActivity。如果我在MainActivity中打印Toast,则它不在上下文对象上包含null指针,但在UseContex中包含的东西却显示null指针异常。

AppComponent

@Singleton @Component(modules = {AppModule.class})
public interface AppComponent {
void inject(DaggerApplication daggerApplication);
void inject(MainActivity mainActivity);


}

应用模块

@Module
public class AppModule {
private final DaggerApplication application;
public AppModule(DaggerApplication application) {
    this.application = application;
}
@Singleton
@Provides
Context providesApplicationContext(){
    return  application;
}
@Singleton
@Provides
UseContex provideUsecontex(){
  return new UseContex();
}
}


UseContex

public class UseContex extends MainActivity{
public  void printToast(){
Log.e("User dao impl","Hello user dao");
Toast.makeText(context, "helo", Toast.LENGTH_SHORT).show();
}
}


主要活动

public class MainActivity extends AppCompatActivity {
@Inject
UseContex useContex;
@Inject
public Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
((DaggerApplication)getApplication()).getAppComponent().inject(this);
     useContex.printToast();
}
}


Dagger应用

public class DaggerApplication extends Application {
AppComponent appComponent;
@Override
public void onCreate() {
    super.onCreate();
    appComponent = DaggerAppComponent.builder().appModule(new
AppModule(this)).build();
    appComponent.inject(this);

}
public AppComponent getAppComponent(){return  appComponent;}

}

最佳答案

Dagger不会注入您的UseContex子类,因为AppComponent不会@provide一个UseContexAppComponent只是@providing一个MainActivity,您要传入一个UseContex作为其多态基类,并希望它能起作用。相反,在@provide中的UseContex一个AppComponent和Dagger将注入您的基类字段。

07-27 17:21