简体   繁体   中英

how do I inject MainActivity context using dagger2 in java?

I am trying to inject the context of the MainActivity into a class I have. I looked at this but it doesn't work for me and I get the following error:

    /home/muhammadmehdi/ALL_PROJECTS/memex/memex-app/app/src/main/java/com/memex/MainActivity.java:30: error: cannot find symbol
import com.memex.components.DaggerMainActivityComponent;
                           ^
  symbol:   class DaggerMainActivityComponent
  location: package com.memex.component

This is the code that I wrote in the onCreate method of the MainActivity.java file:

MainActivityComponent mainActivityComponent = DaggerMainActivityComponent.builder()
                .mainActivityModule(new MainActivityModule(MainActivity.this))
                .build();

Finally figured it out:

// modules.java
@Module
public class ContextModules {

    private final Context context;

    public ContextModules(Context context) {
        this.context = context;
    }

    @Provides
    ContextProviderClass contextProvider() {
        return new ContextProviderClass(context);
    }
}

//components.java interface
@Component(modules = ContextModules.class)
public interface Components {
     // put getter for class that needs context
}

// MainActivity.java where you want the object of class
Components components = DaggerComponents.builder()
                .modules(new ModContextModulesules(this))
                .build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM