What is wrong with RoboGuice

纵饮孤独 提交于 2019-12-13 05:31:08

问题


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

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


回答1:


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

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



回答2:


Also consider if there is necessity to use 'new' operator to create e Object. This always implicate some problems especially in (unit)tests.



来源:https://stackoverflow.com/questions/17062640/what-is-wrong-with-roboguice

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