Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top