我刚开始在我的项目中使用Dagger。我已经创建了以下这些模块:
@Module
public class FirebaseModule {
@Provides @Singleton
public FirebaseUser provideCurrentUser(){
return FirebaseAuth.getInstance().getCurrentUser();
}
@Provides @Singleton
public DatabaseReference provideDatabaseReference(){
return FirebaseDatabase.getInstance().getReference();
}
@Provides @Singleton
public FirebaseAuth provideFirebaseAuth(){
return FirebaseAuth.getInstance();
}
}
而且这个:
@Module
public class AppModule
{
private HappyParkApp app;
public AppModule(HappyParkApp app) {
this.app = app;
}
@Provides
public HappyParkApp providesApp()
{
return this.app;
}
@Provides
public Context getAppContext(){
return this.app;
}
}
我也制作了这个组件:
@Singleton
@Component(modules = {AppModule.class,
FirebaseModule.class})
public interface AppComponent {
void inject(MainActivity activity);
}
这是应用程序中实现的appComponent:
public class HappyParkApp extends Application {
private AppComponent appComponent;
private static HappyParkApp instance = new HappyParkApp();
@Override
public void onCreate() {
super.onCreate();
createAppComponent();
}
public static HappyParkApp getInstance() {
return instance;
}
public AppComponent createAppComponent() {
if(appComponent == null){
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.firebaseModule(new FirebaseModule()).build();
}
return appComponent;
}
所以我已经试图在MainActivity的onCreate()
方法中实现这个: }
HappyParkApp.getInstance().createAppComponent().inject(this);
还有这个:
@Inject
FirebaseUser user;
@Inject
DatabaseReference reference;
@Inject
FirebaseAuth mAuth;
但是我遇到了这个错误:
Caused by: java.lang.NullPointerException: Cannot return null from a non-@Nullable @Provides method
在这一行: HappyParkApp.getInstance().createAppComponent().inject(this);
我不知道如何修复它:是什么错误?这是错误的注入吗?
谢谢你