Reputation: 1969
I'm newbe in Roboguice, please help. I have an application calss MyApplication
in which in onCreate
method i initialize some data. Also i have a POJO
with buisiness logic which i want to use in my MainActivity
(See code snippets below). I need to inject MyApplication
into POJO
to get access to data which i initialize in application's onCreate
, but this code called before onCreate
and i've got a NullPointerException
.
public class MyApplication extends Application {
private Properties applicationProperties;
@Override
public void onCreate() {
super.onCreate();
applicationProperties = loadApplicationProperties(APPLICATION_PROPERTIES_ASSET);
}
@SuppressWarnings("unchecked")
public String getProperty(String key) {
return applicationProperties.getProperty(key);
}
}
@Singleton
public class POJO {
@Inject
private MyApplication application;
@Inject
public void init() {
// NPE here, because application onCreate not called at this moment
serverURL = application.getProperty(Constants.SERVER_URL);
}
}
public class MainActivity extends RoboActivity {
@Inject
private POJO myPOJO;
}
Upvotes: 4
Views: 2055
Reputation: 1407
If the data you need doesn't require a context, just access to XML resources or res/raw, you can inject that from anywhere.
Just use Roboguice.getInjector()
to obtain a copy of the Resources object.
Upvotes: 1
Reputation: 25137
EDIT: Found a way to do this in RoboGuice 2.0 based on the answer in RoboGuice custom module application context.
Inject the application context in AbstractModule constructor, then bind it in configure()
for later injection:
public final class MyModule extends AbstractModule
{
private final MyApplication context;
@Inject
public MyModule(final Context context)
{
super();
this.context = (MyApplication)context;
}
@Override
protected void configure() {
bind(MyApplication.class).toInstance(context);
}
}
Upvotes: 3