在使用UseContex类的'printToast()'方法时,UseContex类上的Null指针异常.UseContex类扩展了mainActivity.If我在MainActivity中打印吐司比在上下文对象中不包含空指针但在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();
}
}
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();
}
}
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;}
}
答案 0 :(得分:0)
Dagger没有注入您的UseContex
子类,因为AppComponent
没有@provide
UseContex
。 AppComponent
只有@providing
和MainActivity
,并且您传递的是UseContex
作为其多态基类,并希望它可以正常工作。相反,@provide
中的UseContex
AppComponent
和Dagger会注入您的基类字段。
答案 1 :(得分:-1)
显示空指针,因为在UseContex类中未定义上下文。 您必须使用“getApplicationContext”代替此行中的“context”
Toast.makeText(context, "helo", Toast.LENGTH_SHORT).show();
替换
Toast.makeText(getApplicationContext, "helo", Toast.LENGTH_SHORT).show();