Search code examples
androidroboguice

Roboguice creates its own Application class instance


I'm using Roboguice for DI in my project. As per android documentation only one instance of application can exists. But instances which crated by OS and by Roboguice is different.

How to force Roboguice inject application created by OS and disable creation of new instance?

Some code which illustrates situation below

public class MyApplication extends Application {

    public static MyApplication getInstance() {
        if (instance == null) {
            throw new IllegalStateException("Application isn't initialized yet!");
        }
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }
}

public class MyActivity extends RoboActivity {

    // roboApp and osApp two different objects but expected that roboApp the same as osApp        

    @Inject
    private MyApplication roboApp;

    private MyApplication osApp = MyApplication.getInstance();

}

Solution

  • RoboGuice doesn't call MyApplication.getInstance() but will instead call new MyApplication()

    You can write a Provider that calls MyApplication.getInstance() instead. This would look like:

     public MyAppProvider implements Provider<MyApplication> {
         @Override
         public MyApplication get() {
             return MyApplication.getInstance();
         }
     }
    

    You can then bind this in your module like: bind(MyApplication.class).toProvider(MyAppProvider.class);