What is wrong with RoboGuice
Asked Answered
B

2

0

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.

Bathelda answered 12/6, 2013 at 9:59 Comment(0)
G
0

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);
Greenhead answered 12/6, 2013 at 10:8 Comment(1)
I got it and I did it and it worked! Thank you! I prefered to use @Inject. So, I declared it near SessionService a variable with the annotation.Bathelda
D
0

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

Dorise answered 22/7, 2013 at 8:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.