详细信息
UseContex类上的空指针异常,同时使用UseContex class.UseContex类的'printToast()‘方法扩展了在MainActivity中打印don的mainActivity.If,而不是它在上下文对象上不包含空指针,但是在UseContex中显示空指针异常的东西是相同的。
AppComponent
@Singleton @Component(modules = {AppModule.class})
public interface AppComponent {
void inject(DaggerApplication daggerApplication);
void inject(MainActivity mainActivity);}
AppModule
@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();
}
}MainActivity
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();
}
}DaggerApplication
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;}
}发布于 2017-06-17 07:48:19
Dagger没有注入您的UseContex子类,因为AppComponent没有@provide a UseContex。AppComponent只是一个@providing,一个MainActivity,您正在将一个UseContex作为它的多态基类传递给它,并希望它能够工作。相反,@provide在AppComponent和Dagger中的一个UseContex将注入您的基类字段。
发布于 2017-06-19 05:35:43
它显示空指针,因为上下文不是在UseContex类中定义的。您必须使用"getApplicationContext“来代替该行中的”上下文“。
Toast.makeText(context, "helo", Toast.LENGTH_SHORT).show();替换
Toast.makeText(getApplicationContext, "helo", Toast.LENGTH_SHORT).show();https://stackoverflow.com/questions/44601578
复制相似问题