gpt4 book ai didi

android - dagger2 非@Nullable @Provides 方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:57:01 26 4
gpt4 key购买 nike

我刚开始在我的项目中使用 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);

而且我不知道如何解决:错误是什么?这是错误的注入(inject)吗?

谢谢

最佳答案

Cannot return null from a non-@Nullable @Provides method

您尝试从标记为@Nullable 的提供程序方法中提供null

看看getCurrentUser()

Returns the currently signed-in FirebaseUser or null if there is none.

因此,如果没有登录用户,这将为 null,从而使以下无效...

@Provides @Singleton
public FirebaseUser provideCurrentUser(){
return FirebaseAuth.getInstance().getCurrentUser(); // could be null!
}

所以要修复它,您有 2 个选择:

  • 提供 FirebaseAuth 并在您的应用程序代码中获取用户,或者
  • 将提供者标记为@Nullable

哪种方法更好取决于您的设置,但由于您将用户放在 @Singleton 范围内的组件中,我建议不要提供用户,因为它很可能在“单例”的生命周期内改变。

要么将其移动到不同的范围(例如 @UserScope@PerUser),要么使用 FirebaseAuth.getCurrentUser() 在您需要的地方抓取用户。您仍然可以提供 FirebaseAuth

还有 read about nullability here .

关于android - dagger2 非@Nullable @Provides 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43763293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com