Thomas Kaliakos
Thomas Kaliakos

Reputation: 3304

Roboguice 2.0 @Inject a singleton into a POJO

I have a created a Settings class annotated with @Singleton. This class is successfully injected in my RoboActivities. However when I try to inject it to a POJO (plain old java object), I get a null pointer exception (i.e. is not injected). This POJO is instantiated in a different thread (I don't know if it is relevant). And one last thing, do I have to explicitly create the default constructor of a class if I want to inject instances of that class?
Thanks for any help,
Thomas

Upvotes: 1

Views: 1712

Answers (2)

Abs
Abs

Reputation: 3962

This link is a good explanation of the singleton with roboguice:

It explains a very important caveat/anti pattern.

Astroboy Example

@Singleton
public class Astroboy {
    // Because Astroboy is a Singleton, we can't directly inject the current Context
    // since the current context may change depending on what activity is using Astroboy
    // at the time.  Instead, inject a Provider of the current context, then we can
    // ask the provider for the context when we need it.
    // Vibrator is bound to context.getSystemService(VIBRATOR_SERVICE) in RoboModule.
    // Random has no special bindings, so Guice will create a new instance for us.
    @Inject
    Provider<Context> contextProvider;
    @Inject
    Vibrator vibrator;
    @Inject
    Random random;

    public void say(String something) {
        // Make a Toast, using the current context as returned by the Context
        // Provider
        Toast.makeText(contextProvider.get(),
                "Astroboy says, \"" + something + "\"", Toast.LENGTH_LONG)
                .show();
    }

    public void brushTeeth() {
        vibrator.vibrate(
                new long[] { 0, 200, 50, 200, 50, 200, 50, 200, 50, 200, 50,
                        200, 50, 200, 50, 200, 50, 200, 50, 200, 50, 200, 50, },
                -1);
    }

    public String punch() {
        final String expletives[] = new String[] { "POW!", "BANG!", "KERPOW!",
                "OOF!" };
        return expletives[random.nextInt(expletives.length)];
    }
}

Upvotes: 0

Thomas Kaliakos
Thomas Kaliakos

Reputation: 3304

My bad, The problem was that I wasn't instantiating the POJO that belonged to another class using:

RoboGuice.getInjector(context).injectMembers(this);

Upvotes: 2

Related Questions