Java Dagger-2(android)的空指针异常 细节

Java Dagger-2(android)的空指针异常 细节,java,android,dagger-2,dagger,Java,Android,Dagger 2,Dagger,使用UseContex类的“printToast()”方法时UseContex类上出现空指针异常。UseContex类扩展了mainActivity。如果我在mainActivity中打印toast,则它不会在上下文对象上包含空指针,但在UseContex中不包含相同的内容,而会显示空指针异常 应用组件 } 应用模块 UseContex 主要活动 匕首应用 Dagger没有注入您的UseContex子类,因为AppComponent没有@提供UseContexAppComponent只是提供了一

使用UseContex类的“printToast()”方法时UseContex类上出现空指针异常。UseContex类扩展了mainActivity。如果我在mainActivity中打印toast,则它不会在上下文对象上包含空指针,但在UseContex中不包含相同的内容,而会显示空指针异常

应用组件 }

应用模块 UseContex 主要活动 匕首应用
Dagger没有注入您的
UseContex
子类,因为
AppComponent
没有
@提供
UseContex
AppComponent
只是提供了一个
MainActivity
,您正在将一个
UseContex
作为多态基类传递给它,并希望它能起作用。相反,
@在
AppComponent
中提供
UseContex
,Dagger将注入基类字段

它显示空指针,因为上下文未在UseContex类中定义。 您必须使用“getApplicationContext”来代替此行中的“context”

Toast.makeText(context, "helo", Toast.LENGTH_SHORT).show();
替换

Toast.makeText(getApplicationContext, "helo", Toast.LENGTH_SHORT).show();

如果在我的AppComponent中@provide UseContex显示错误Yup,则需要在AppComponent中添加一个@provide方法,该方法返回UseContext,并向您询问最佳答案。你能在你的另一个问题上也试一下我的答案吗?
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;}

}
Toast.makeText(context, "helo", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext, "helo", Toast.LENGTH_SHORT).show();