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

时间:2017-06-17 06:35:32

标签: java android dagger-2 dagger

详细

在使用UseContex类的'printToast()'方法时,UseContex类上的Null指针异常.UseContex类扩展了mainActivity.If我在MainActivity中打印吐司比在上下文对象中不包含空指针但在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;}

}

2 个答案:

答案 0 :(得分:0)

Dagger没有注入您的UseContex子类,因为AppComponent没有@provide UseContexAppComponent只有@providingMainActivity,并且您传递的是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();