Search code examples
androiddependency-injectionroboguicedagger

Inject object Resources in Class Util (using Dagger)


I some time testing some things with Dagger, after overseeing the series of articles here: http://antonioleiva.com/dependency-injection-android-dagger-part-1/, went back for more information, I saw some good examples like these: https://github.com/adennie/fb-android-dagger, most of which focuses on injecting dependencies on Activity, Fragment, Service and related. I'm wanting to do a similar thing with RoboGuice.

In RoboGuice

public class Utils {

    @InjectResource(R.string.hello_world) private String hello;

    public void showLog(){
        System.out.println("String from injected resource : " + hello);
    }
}

In Dagger

public class Utils {

    @Inject
    Resources mResource;

    public void showLog() {
        System.out.println( "String from injected resource : "  + this.mResource.getString( R.string.hello_world ) );
    }
}

I created an module in my Application:

@Module( injects = {Utils.class }, complete = false, library = true )
public class ResourceModule {

    Context mContext;

    public ResourceModule ( final Context mContext ) {
        this.mContext = mContext;
    }

    @Provides
    @Singleton
    Resources provideResources() {
        return this.mContext.getResources();
    }
}

Tried this in my Activity

Utils mUtils = new Utils();
mUtils.showLog();

But I'm getting NullPointerException. Someone already did something similar?


Solution

  • You have to inject the object using inject method.

    Assuming your ObjectGraph is initialized in the App class which is a subclass of the Application and exposes public inject method with implementation like below:

    public void inject(Object object) {
        mObjectGraph.inject(object);
    }
    

    After creating the Utils instance you have to inject its dependencies.

    Utils mUtils = new Utils();
    ((App) getApplication).inject(mUtils);
    mUtils.showLog();
    

    Edit:

    You can also use constructor injection (no need for passing the object to ObjectGraph)

    public class Utils {
    
        private final Resources mResource;
    
        @Inject
        public Utils(Resources resources) {
            mResources = resources;
        }
    
        public void showLog() {
            System.out.println( "String from injected resource : "  + this.mResource.getString( R.string.hello_world ) );
        }
    }
    

    With constructor injection the object must be created by the ObjectGraph

    Utils mUtils = mObjectGraph.get(Utils.class);