【问题标题】:What is wrong with RoboGuiceRoboGuice 有什么问题
【发布时间】:2013-06-12 09:59:01
【问题描述】:

我想使用 RoboGuice 创建一个单例对象,但我得到空异常。我不知道我的代码有什么问题。

 @Singleton
    public class SessionService {

        private static Session session;

        public Session getSession() {
            if (session == null){
                session = new Session();
            }
            return session;
        }

    }

--

public class ChannelManager {

    @Inject SessionService sessionService;

    public String getName(){
        return sessionService.getSession().getName();
    }

}

public class MainActivity extends RoboActivity{

    @InjectView(R.id.button1) Button btn;
    @Inject SessionService a;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
            a.getSession().setName("dsadas");
        Log.i("A","NEW: "+ a.getSession().getName());
        Log.i("A","NEW NAME: "+ new ChannelManager().getName());        
    }

我在“new ChannelManager().getName()”行上得到空异常。那有什么问题? 提前致谢。

【问题讨论】:

    标签: android roboguice


    【解决方案1】:

    当你做new ChannelManager()时,你没有使用Guice注入,所以你注入的字段是空的。

    要注入您的ChannelManager,请使用@Inject 注释或使用以下代码创建您的实例:

    ChannelManager myChannelManager = RoboGuice.getInjector(this).getInstance(ChannelManager.class);
    

    【讨论】:

    • 我明白了,我做到了,而且成功了!谢谢!我更喜欢使用@Inject。所以,我在 SessionService 附近声明了一个带有注释的变量。
    【解决方案2】:

    还要考虑是否有必要使用'new'操作符来创建e Object。这总是暗示一些问题,尤其是在(单元)测试中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 2014-08-12
      • 2010-12-23
      • 2010-10-24
      相关资源
      最近更新 更多