Cant inject classes using Dagger on Android - android

I am beggining with Dagger, I am using 1.2 version of it, and I have the following scenario:
Module:
#Module(injects = {
AuthenticationService.class
})
public class ServiceModule {
#Provides
AuthenticationService provideAuthenticationService() {
return ServiceFactory.buildService(AuthenticationService.class);
}
}
On my Application class I create the ObjectGraph:
public class FoxyRastreabilidadeApplication extends Application {
private static FoxyRastreabilidadeApplication singleton;
#Override
public void onCreate() {
super.onCreate();
createObjectGraph();
singleton = this;
}
private void createObjectGraph() {
ObjectGraph.create(ServiceModule.class);
}
}
and finally, at my LoginActivity, I try to inject my AuthenticationService:
public class LoginActivity extends Activity implements LoaderCallbacks<Cursor> {
private UserLoginTask mAuthTask = null;
#Inject
AuthenticationService authenticationService;
}
At this point, when I try to access my AuthenticationService instance it is always null, meaning it wasnt injected at all, I debugged my provider method to be sure of it, so, the question is, am I missing something? If so, what is it?

You need to hold on to the ObjectGraph and ask it to inject your objects directly.
Add an instance variable to your custom Application subclass to hold on to the created ObjectGraph:
this.objectGraph = ObjectGraph.create(ServiceModule.class);
Add a convenience method to your Application to do injection:
public void inject(Object object) {
this.objectGraph.inject(object);
}
Call that method wherever you need injection to happen, for example in your Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MyApplication)getApplication()).inject(this);
...
}

Related

Mock injected ViewModel

I need to run Android instrumented test on StarterActivity. Here is how it goes
public class StarterActivity extends BaseActivity<ActivityStarterBinding> {
#Inject
protected StarterViewModel starterViewModel;
#Override
public int getContentView() {
return R.layout.activity_starter;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getApplicationComponent().inject(this);
}
//...
}
And I call for starterViewModel method in onStart.
StarterViewModel is injected via a constructor:
public class StarterViewModel {
private final AuthDataModel authDataModel;
#Inject
public StarterViewModel(AuthDataModel authDataModel) {
this.authDataModel = authDataModel;
}
#NonNull
public Single<Boolean> isUserLoggedIn() {
return authDataModel.isUserLoggedIn();
}
}
I found this really nice approach Android testing using Dagger 2, Mockito and a custom JUnit rule. But it needs me to add #Provide method. And application component is going to become "God component" with dependencies on a bunch of Modules (or one "God module").
How can I mock in Espresso test without adding #Provide method and overriding it in tests?

Activity graphs and non-found dependency

I'm starting using the dagger, like it pretty much, but now facing some difficulties. My scenario is as follows: there's an activity and a dependency for it. Dependency is injected to the activity, and requires a reference to that activity. Just like this:
public class MainActivity extends BaseActivity {
#Inject ScbeHelper scbeHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
}
public class ScbeHelper {
protected static final String TAG = "scbe_helper";
private BaseActivity activityContext;
#Inject
public ScbeHelper(BaseActivity context) {
this.activityContext = context;
}
}
I'm following dagger's example from the github for activity's graphs. So I've created a similar structure in my project. First, the BaseActivity class, from which MainActivity is inherited:
public abstract class BaseActivity extends Activity {
private ObjectGraph activityGraph;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
protoApp application = (protoApp) getApplication();
// Exception happens in next line, inside plus() method
activityGraph = application.getApplicationGraph().plus(getModules().toArray());
// Inject ourselves so subclasses will have dependencies fulfilled when this method returns.
activityGraph.inject(this);
((protoApp)getApplication()).inject(this);
}
protected List<Object> getModules() {
return Arrays.<Object>asList(new ActivityModule(this));
}
public void inject(Object object) {
activityGraph.inject(object);
}
}
And the module:
#Module(injects={MainActivity.class})
public class ActivityModule {
private final BaseActivity activity;
public ActivityModule(BaseActivity activity) {
this.activity = activity;
}
#Provides #Singleton BaseActivity provideActivity() {
return activity;
}
}
Now, the problem: No injectable members on com.example.proto.BaseActivity. Do you want to add an injectable constructor? required by public com.example.proto.ScbeHelper(com.example.proto.BaseActivity)
In other words, provider method ActivityModule.provideActivity() doesn't really provide the instance of BaseActivity for some reason, though in my understanding it's set up correctly. Does anyone see an error in my setup? Am I missing something in dagger's logic?
Thanks in advance!
I'm no Dagger expert, but you have 2 issues:
you have a cyclical dependency: you helper want to have the activity injected, your activity wants to have the helper injected. I don't think Dagger can resolve this
your activity tries to get injected twice, once with the activity-level graph, once with the application-level graph
Here's what I did to get it to work:
in ScbeHelper: remove the #Inject annotation
in BaseActivity: remove ((protoApp)getApplication()).inject(this);
in ActivityModule: remove your provideActivity method (it's not going to be used anymore), and add the following method:
#Provides #Singleton ScbeHelper provideScbeHelper() {
return new ScbeHelper(activity);
}
What this does is it provides your ScbeHelper with the context it needs, but leaves only 1 annotation-driven injection so dagger can resolve it. Hope this helps.

Dagger and dependecies on provided classes

I am "Daggering" my Android app and I am facing a little problem that I don't know if it's me or framework's fault. If it's me I will be very disappointed by myself :)
I have the following class to provide:
#Singleton
public class XmlService {
private final DataCommitter<XmlWritable> mXmlCommitter;
private final DataReader<XmlPushable> mXmlReader;
private final ConcurrentObjectMonitor mConcObjMonitor;
#Inject
public XmlService(DataCommitter<XmlWritable> xmlCommitter,
DataReader<XmlPushable> xmlProvider,
ConcurrentObjectMonitor concObjMonitor) {
mXmlCommitter = xmlCommitter;
mXmlReader = xmlProvider;
mConcObjMonitor = concObjMonitor;
}
With the following (among the others) class:
public class XmlDataReader implements DataReader<XmlPushable> {
// No Singleton no more.
// Eager Singleton (Therefore it should be made thread safe)
//static XmlDataReader mInstance = new XmlDataReader();
[CUT]
protected XmlPullParser mXmlPullParser;
#Inject
public void XmlDataRead(XmlPullParser xmlPullParser) {
mXmlPullParser = xmlPullParser;
}
This class is referred in my XmlServiceModule like this:
#Module(complete = true)
public class XmlServiceModule {
#Provides DataReader<XmlPushable> provideDataReader(XmlDataReader dataReader) {
return dataReader;
}
}
Now, the question is, is it legal to Inject provided classes? Because I am getting an error with the #Inject on the XmlDataReader ctor: Cannot inject public void XmlDataRead(org.xmlpull.v1.XmlPullParser).
EDIT: sorry guys, there was an error in my sample code, but I will leave it as is, because it can be useful in order to understand Christian's answer below.
Actually, you have an error in your sample code. You have no injectable constructor - you cannot inject an instance method, only a constructor, and that method is never called.
You should have:
public class XmlDataReader implements DataReader<XmlPushable> {
protected final XmlPullParser mXmlPullParser;
#Inject
public XmlDataReader(XmlPullParser xmlPullParser) {
mXmlPullParser = xmlPullParser;
}
}
This way it's a constructor, and will be properly injected.
As to the overall approach, you're in the right direction. You #Provide DataReader<XmlPushable, and effectively bind XmlDataReader to it in your provides method. So far so good. Dagger, when asked for DataReader<XmlPushable> will use that binding, and will effectively pass-through the dependency and provide XmlDataReader to satisfy this.
XmlDataReader has an #Inject annotated constructor, so Dagger's analysis will see it as an "injectable type" so you don't need an #Provides to provide it. As long as you either have an XmlPullParser that either has an #Inject annotated constructor or is provided in an #Provides method on a module, what you've coded here seems good, but is not quite complete.
You don't have any entryPoints listed in your #Module, and you must have a class that will be the first thing you obtain from the ObjectGraph. So this code is reasonable as far as it goes, but incomplete. You need something that injects (through a field or constructor) DataReader<XmlPushable> For example, you might make a FooActivity which does this.
Consider:
public class XmlDataReader implements DataReader<XmlPushable> {
protected XmlPullParser mXmlPullParser;
#Inject public XmlDataReader(XmlPullParser xmlPullParser) {
mXmlPullParser = xmlPullParser;
}
}
#Module(entryPoints = { FooActivity.class, BarActivity.class })
public class XmlServiceModule {
#Provides DataReader<XmlPushable> provideDataReader(XmlDataReader dataReader) {
return dataReader;
}
#Singleton
#Provides XmlPullParserFactory parserFactory() {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
return factory;
}
#Provides XmlPullParser parser(XmlPullParserFactory factory) {
XmlPullParser xpp = factory.newPullParser();
}
}
public class YourApp extends Application {
private ObjectGraph graph;
#Override public void onCreate() {
super.onCreate();
graph = ObjectGraph.get(new ExampleModule(this));
}
public ObjectGraph graph() {
return objectGraph;
}
}
public abstract class BaseActivity extends Activity {
#Override protected void onCreate(Bundle state) {
super.onCreate(state);
((YourApp) getApplication()).objectGraph().inject(this);
}
}
class FooActivity extends BaseActivity {
#Inject DataReader<XmlPushable> reader;
#Override public void onCreate(Bundle bundle) {
super.onCreate(bundle);
// custom Foo setup
}
}
class BarActivity extends BaseActivity {
#Inject DataReader<XmlPushable> reader;
#Override public void onCreate(Bundle bundle) {
super.onCreate(bundle);
// custom Bar setup
}
}
This is probably close to what you want. All things are reachable from an entry point, and all things you depend on are bound. The two Activities are your "entry points" (roots in the object graph). When they are initialized, they ultimately call the ObjectGraph's inject(Object) method on themselves, which causes Dagger to inject any #Inject annotated fields. Those fields are the DataReader<XmlPushable> fields, which is satisfy by XmlDataReader, which is provided with an XmlPullParser, which is provided by using a XmlPullParser. It all flows down the dependency chain.
Small note - #Module(complete=true) is the default. You don't need to specify complete, unless it's incomplete and you specify false

Roboguice creates its own Application class instance

I'm using Roboguice for DI in my project. As per android documentation only one instance of application can exists. But instances which crated by OS and by Roboguice is different.
How to force Roboguice inject application created by OS and disable creation of new instance?
Some code which illustrates situation below
public class MyApplication extends Application {
public static MyApplication getInstance() {
if (instance == null) {
throw new IllegalStateException("Application isn't initialized yet!");
}
return instance;
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
public class MyActivity extends RoboActivity {
// roboApp and osApp two different objects but expected that roboApp the same as osApp
#Inject
private MyApplication roboApp;
private MyApplication osApp = MyApplication.getInstance();
}
RoboGuice doesn't call MyApplication.getInstance() but will instead call new MyApplication()
You can write a Provider that calls MyApplication.getInstance() instead. This would look like:
public MyAppProvider implements Provider<MyApplication> {
#Override
public MyApplication get() {
return MyApplication.getInstance();
}
}
You can then bind this in your module like: bind(MyApplication.class).toProvider(MyAppProvider.class);

Roboguice 2.0 injecting application into POJO

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

Categories

Resources