Inject object Resources in Class Util (using Dagger)
Asked Answered
V

1

6

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?

Variole answered 16/7, 2014 at 14:57 Comment(0)
P
2

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);
Psychognosis answered 16/7, 2014 at 16:0 Comment(3)
but what can otherwise without explicitly passing the object to ObjectGraph?Variole
@André.C.S check the updated answer. I've added some information about constructor injectionPsychognosis
First, thanks for listening to my doubts, I know this is a simple matter, and despite the learning curve in this lib be a little big, I'm convinced to use it for process optimization in relation to RoboGuice using reflectionVariole

© 2022 - 2024 — McMap. All rights reserved.