详细信息
使用 UseContex 类的“printToast()”方法时,UseContex 类上出现空指针异常。UseContex 类扩展了 mainActivity。如果我在 MainActivity 中打印 toast,那么它在上下文对象上不包含空指针,但在 UseContex 中也不会包含相同的内容它显示空指针异常。
应用组件
@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();
}
}
使用上下文
public class UseContex extends MainActivity{
public void printToast(){
Log.e("User dao impl","Hello user dao");
Toast.makeText(context, "helo", Toast.LENGTH_SHORT).show();
}
}
主要 Activity
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 没有注入(inject)您的 UseContex
子类,因为 AppComponent
没有 @provide
UseContex
。 AppComponent
只是 @providing
一个 MainActivity
并且您传入 UseContex
作为其多态基类并希望那个有效。相反,AppComponent
中的 @provide
一个 UseContex
和 Dagger 将注入(inject)您的基类字段。
关于java - Dagger-2 的空指针异常(android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44601578/