Search code examples
androiddependency-injectionsharedpreferencesviewmodeldagger-2

How to inject SharedPreferences to a ViewModel using Dagger2 in android java


I am facing a problem while trying to inject SharedPreference to a ViewModel, I am doing the dependency injection using dagger. I will add the main sections of the code below

Module 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);
    }

}

Sub Components are added as given below

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

The error I am getting is given below

error: @Subcomponent.Factory method is missing parameters for required modules or subcomponents:

I understood that the constructor in the SharedPreferencesModule is cauing the error and since the module is added using ContributesAndroidInjector, I cannot able to pass a context to the SharedPreferencesModule. But I need that to get the SharedPreferences

Is there any way to ge rid of this issue.

My BaseApplication code is given below

public class BaseApplication extends DaggerApplication {

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

The reference for the development is from this link Youtube Link

Any help would be much appreciated, Since I had spend a whole day with this.

Note : Any alternate solution I can use, but I cannot break this project structure


Solution

  • You already have two contexts in your Dagger graph: Application and DashboardActivity. To use one of these, simply add it as a dependency in your @Provides method. (If you use DashboardActivity, I would suggest using a @Binds method to bind it to Activity or Context first.)

    For example, to use the Application binding already in your graph:

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