What is wrong with RoboGuice

2019-09-16 23:50发布

问题:

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.