3

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();

}
Dmitriy Tarasov
  • 1,949
  • 20
  • 37
  • How different? Maybe RoboApp is just inheritance of MyApplication? Or they cast to Application so you loose your custom variable? Something like this.. – katit Sep 18 '12 at 17:13
  • Nope, roboApp is the instance of MyApplication but it isn't properly initialized, because RoboGuice doesn't call onCreate during construction – Dmitriy Tarasov Sep 19 '12 at 07:09
  • Dmitriy, I had similar question to yours. In particular I was wondering if it is possible to have 2 instances of Application. Yes, it is possible. For example you can have Service running in different process alltogether and communicate with your app via IPC. Not sure how Robo works but it might be something like that.. – katit Sep 19 '12 at 14:47
  • Looks like this is a very common issue with roboguice.. someone worked it out.. – user210504 Dec 18 '12 at 14:41

1 Answers1

1

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);

Jeroen
  • 3,399
  • 1
  • 22
  • 25