2

How do I get the application context in my custom module? Here is the code for my module:

public class MyModule extends AbstractModule {
    @Override
    @SuppressWarnings("unchecked")
    protected void configure() {
        // Package Info
        try {
            final PackageInfo info = application.getPackageManager().getPackageInfo(
                    application.getPackageName(), PackageManager.GET_META_DATA);
            bind(PackageInfo.class).toInstance(info);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

I am trying to get the metadata for the application. The default module version of PackageInfo doesn't have meta data, hence I need custom binding.

Mandar Limaye
  • 1,900
  • 16
  • 24

1 Answers1

3

Just inject it in constructor

public final class MyModule extends AbstractModule
{
    private final Context   context;

    @Inject
    public MyModule(final Context context)
    {
        super();
        this.context = context;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void configure() {
        // Package Info
        try {
            final PackageInfo info = context.getPackageManager().getPackageInfo(
                context.getPackageName(), PackageManager.GET_META_DATA);
            bind(PackageInfo.class).toInstance(info);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}

Michal Harakal
  • 1,025
  • 15
  • 21
  • I tried this but it didn't work .. I suspect i was missing something obvious. Do you know of a full example of using a custom module with RoboGuice 2.0? The default example with RoboGuice doesn't use custom module. – Mandar Limaye Mar 27 '13 at 04:19
  • @Mubix This part is from a working app. What does it mean, didn't work? In case a context was null or invalid, I would try to inject _ContextProvider_ instead context. – Michal Harakal Mar 27 '13 at 15:30