Roboguice 2.0 (android): POJO injection error (always null)

孤人 提交于 2019-12-25 02:47:15

问题


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:


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.



来源:https://stackoverflow.com/questions/22931569/roboguice-2-0-android-pojo-injection-error-always-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!