有什么不对RoboGuice [英] What is wrong with RoboGuice

查看:174
本文介绍了有什么不对RoboGuice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个使用RoboGuice一个单独的对象,但我得到空例外。我不知道什么是错我的codeS。

I want to create a singleton object using RoboGuice but I get null exception. I don't know what is wrong with my codes.

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

我得到空异常新ChannelManager()的getName()行。这有什么错呢?
先谢谢了。

I get null exception on "new ChannelManager().getName()" line. What's wrong with that? Thanks in advance.

推荐答案

当你做新ChannelManager(),不使用Guice的注入,所以你的注入字段空。

When you do new ChannelManager(), you are not using Guice injection, so your injected fields are null.

要注入你的 ChannelManager ,要么使用 @Inject 注释,使用下面的code创建您的实例:

To inject your ChannelManager, either use the @Inject annotation or use the following code to create your instance:

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

这篇关于有什么不对RoboGuice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆