【问题标题】:How to inject SharedPreferences to a ViewModel using Dagger2 in android java如何在 android java 中使用 Dagger2 将 SharedPreferences 注入 ViewModel
【发布时间】:2020-09-03 13:32:59
【问题描述】:

我在尝试将 SharedPreference 注入 ViewModel 时遇到问题,我正在使用 dagger 进行依赖项注入。我将在下面添加代码的主要部分

模块 SharedPreferencesModule.java

@Module
public class SharedPreferencesModule {

    private Context context;
    public SharedPreferencesModule(Context context) {
        this.context = context;
    }

    @Provides
    public SharedPreferences provideSharedPreferences() {
        return this.context.getSharedPreferences("login",Context.MODE_PRIVATE);
    }

}

添加子组件如下所示

@DashScope
@ContributesAndroidInjector(
        modules = {
        DashboardFragmentBuildersModule.class, D
        ashboardViewModelsModule.class,
        DashboardModule.class,
        SharedPreferencesModule.class // Added Newly for injecting
        }
)
abstract DashboardActivity contibuteDashboardActivity();

我得到的错误如下所示

错误:@Subcomponent.Factory 方法缺少所需模块或子组件的参数:

我知道 SharedPreferencesModule 中的构造函数会导致错误,并且由于模块是使用 ContributesAndroidInjector 添加的,因此我无法将上下文传递给 SharedPreferencesModule。但我需要它来获取 SharedPreferences

有什么办法可以解决这个问题。

我的 BaseApplication 代码如下

public class BaseApplication extends DaggerApplication {

    @Override
    protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
        return DaggerAppComponent
                .builder()
                .application(this)
                .build();
    }
}

开发参考来自此链接Youtube Link

任何帮助将不胜感激,因为我已经花了一整天的时间。

注意:我可以使用任何替代解决方案,但我不能破坏这个项目结构

【问题讨论】:

    标签: android dependency-injection sharedpreferences viewmodel dagger-2


    【解决方案1】:

    您的 Dagger 图中已经有两个上下文:ApplicationDashboardActivity。要使用其中之一,只需将其作为依赖项添加到您的 @Provides 方法中。 (如果你使用DashboardActivity,我建议先使用@Binds 方法将其绑定到ActivityContext。)

    例如,要使用图表中已有的Application 绑定:

    @Module
    public class SharedPreferencesModule {
    
        @Provides
        public static SharedPreferences provideSharedPreferences(Application application) {
            return application.getSharedPreferences("login",Context.MODE_PRIVATE);
        }
    
    }
    

    【讨论】:

    • 酷!谢谢兄弟,你拯救了我的一天 :) 一个问题:这个解决方案是否保持 MVVM 架构没有任何内存泄漏? @nitrodon
    • 是的,你可以在任何应用架构中使用这个模块类,包括 MVVM。此外,SharedPreferences 可以安全地存储在任何地方,而且这个模块不会存储它,所以没有泄漏的风险。
    • 好的,谢谢!还有一件事,请您添加使用Context@BindDashboardActivity 的另一种方式
    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多