Roboguice 2.0 (android): POJO injection error (alw

2019-08-31 03:29发布

My base POJO class:

public class BaseDao {
   public BaseDao() {
   }
   // ... 
}

My extends POJO class:

public class KelvinDao extends BaseDao {
   public KelvinDao () {
      super();
   }
   // ... 
}

I want to use KelvinDao in a service like that:

public class HanKelvinHandler extends HttpRequestHandler {

   @Inject
   private KelvinDao mKelvinDao;

   public void treatGet() {
      mKelvinDao.blabla(); !!! mKelvinDao is always NULL
   }

It's really simple but it doesn't work :(

Thank you guys for your help!

1条回答
2楼-- · 2019-08-31 03:56

How are you creating HanKelvinHandler? If you're doing it within a subclass of a RoboGuice class, such as RoboActivity, then it should just work. Example:

public class MyActivity extends RoboActivity
{
    @Inject
    private HanKelvinHandler m_handler;
    [...]
}

Otherwise (i.e., you're creating it within another POJO), you're in regular Guice land, and I believe you will need to use the injector to get an instance of it. Example:

public class MyClass
{
    public void doSomething()
    {
        Injector injector = Guice.createInjector( new YourGuiceBindings() );
        HanKelvinHandler handler = injector.getInstance( HanKelvinHandler.class );
        handler.treatGet(); // mKelvinDao should be good now
    }
}

If you haven't seen the use of the injector before, or you don't know what to put for YourGuiceBindings(), then you may need to read the following:

https://github.com/roboguice/roboguice/wiki/Simple-Custom-Binding

https://code.google.com/p/google-guice/wiki/GettingStarted

It seems like there should be a way to do this without using the injector, but I don't know.

查看更多
登录 后发表回答