Dagger and AndroidAnnotations - how to inject #Pref, #Bean, etc? - android

I'm using AndroidAnnotations in my project and just hooked Dagger + Robolectric + Espresso in.
Currently I have an Activity with SharedPrefences and a class 'injected' by AndroidAnnotations.
public class SomeActivity extends Activity {
#Pref Prefs_ prefs;
#Bean SomeManager mManager;
}
Now if I want to use a Dagger to inject these two, what my #Provide methods should look like?
Thank you very much.

Your #Provide methods should call the getInstance_ method of generated bean classes. This methods creates a new instance and injects the necessary objects. For the generated preference, you should call the constructor new Prefs_(context). However, this is not a too clean way since these generated methods are supposed to called by AA. Also Dagger integration is only working in the snapshot release, check out this thread. But as you can see, you can use Dagger now, but it is not convenient, and it seems to be better to just use AA injection for the AA generated classes for now.

Related

Use Dagger2 Android Injection Support without specifying the class name

Is there a way in Dagger2 or in Dagger2 Android Injection support to inject the member instances without specifying the class names of the fragments.
I have a modular project where
The following line is asking to provide a binder Factory for the injectable class.
#Override
public void onAttach(Context context) {
AndroidSupportInjection.inject(this);
super.onAttach(context);
}
But my intention is to provide the injecting members through different modules in the project, where the I wouldn't need to specify the class name of the Fragment at all.
Is this possible in Dagger2 injection or not?
Is there a way in Dagger2 or in Dagger2 Android Injection support to inject the member instances without specifying the class names of the fragments.
tl;dr No. You always need a component that contains a .inject(FragmentInQuestion fragment) method for every Fragment you want to inject.
Dagger uses annotation processing at compile time to resolve all of your .inject(SomeFragment fragment) methods where it looks up fields annotated with #Inject and creates code to inject them.
It needs the actual class name, since it will only generate code for the class used with its fields.
class Fragment {
// no #Inject annotated fields, part of framework!
}
class SomeFragment extens Fragment {
#Inject SomeDependency dep;
}
class OtherFragment extens Fragment {
#Inject OtherDependency dep;
}
Declaring one generic component that injects all your fragments is impossible.
.inject(Fragment fragment) would not inject any properties, since Fragment does not contain any #Inject annotated fields. So neither of the dep fields in the above sample would be provided and they both would be null.
You could create a BaseFragment that contains common objects and write an injection for it, but again, any annotated fields of its children would not be supplied.
You could try some other workarounds, but in the end it would always mean that you'd be injecting or be working with a base type. While this might be feasible in some situations, I don't think it would work on more than some special edge cases.
The Android Injection part of Dagger 2 takes this approach and creates a generic interface that your components have to implement along with a Builder to bind the type in question.
interface AndroidInjector<T> {
inject(T instance)
}
By implementing this interface AndroidInjection can then look up (and create) the correct component and inject your Fragment. For the reasons mentioned above this will always be the actual class of your Fragment, and not some base type.
So by using the Android Injection part you won't be able to use some common base class, and even without it you'd have a hard time.
If you're looking for a way to move out the call of AndroidInjection.inject(this) to somewhere else you should look at the Google Android Architecture Components sample project where they use FragmentLifecycleCallbacks to inject the fragments globally at the right time.

Context in MVVM in android

I have started working on MVVM architecture for android application.I have a doubt that is it right to pass the context to view model ? If not then how can my view model can access the context if needed.
I am doing the following things:
Feed data using some EditText.
Send this data to View model.
View model send this data to repository
Repository storing this data to shared preferences of the device.
As shared preferences required context to instantiate the object.
I am new to this architecture any guidance would be helpful for me, thanks in advance.
I think the use of ApplicationContext is ok, You can extend your ViewModel from AndroidViewModel and whenever you need a reference to the context use getApplication() methods.
Even better, if your using dagger, you don't need this at all, you just inject your ApplicationContext where ever you need it. It can be in your view model or a utility class that handles shared preference, etc.
UPDATE 2019
I don't want to mislead anyone with my old post, so figured I better update it.
With the latest release of the architectural components and JetPack, MVVM is now a real competitor for actual proper structure of breaking apart the code base in a very clean way.
The View is the Activity or Fragment along with the xml that is inflated basically (that's a bit of a weird MVVM, I know, but let's roll with it).
The ViewModel is the actual ViewModel classes offered now with lifecycle scopes and observers. Due to these new features, and life cycle management tools, the ViewModel is very nice at maintaining the data for the view while accessing the Repository Layer of Room DB or Retro API for fetching appropriate LiveData, Observable Data or just standard Models.
I'll leave this here as I feel it was very relevant during the earlier pre Architecture Implementation Days, but if you are not using the Architecture Components and JetPack, Boy are you missing out lol. Code is getting so much cleaner and smaller. :)
OLD REPLY
This is a long debated discussion among the Android community. When we refer to MVC it is obvious that Models (aka data holding objects) are the M, Controllers = C for the Activity classes (in iOS they actually call them UIViewControllers) and the V for the View in Android is the XML file itself. Now some would argue the architectural breakdown of what represents what. However, let's move past this and discuss MVVM.
MVVM has been around for many years now. There have been a few attempts in the past to bring it to Android through 3rd party binding tools, but it ends up more hacky then it is worth.
Recently with the release of native Data Binding Android is finally capable of doing a somewhat clean implementation of MVVM. So there are a couple options here. You can do
M = Models (data holding objects)
V = Views (the XML file itself representing the UI)
VM = This is where debates occur.
Some say in order to be a "true" ViewModel one must have true separation from the Presentation layer and the Activity class itself has lifecycle callbacks thus making it unworthy of being known as the ViewModel.
Others would point out that in order to handle most of the actions triggered from the ViewModel one must have an awareness of onActivityResult, onNewIntent, onBroadcastReceived, onPause or other life cycle handlings to appropriately manage the user experience. So On my team we consider the Activity as the ViewModel. Otherwise you are passing the activity down to a viewmodel and tightly coupling the two anyways, making a giant hideous maintenance nightmare of code.
So you if you want my opinion, stick to treating the Activity as your ViewModel. Get your data to the ViewModel just like any other binding technology like INotifyPropertyChanged in WPF. You do it through your Binding.
I do two things to make this happen. One I have an Activity variable in the XML layout to inject in the onCreate for the binding setup which gives the XML direct binding rights to any observable properties in the viewModel aka the activity. Then I inject whatever variables I need to make use of as well for example you may have a WeatherModel that populates a forecast that lives within the Activity that you would also set in the onCreate to allow the XML access to both it's ViewModel (aka activity) and it's viewModel's Objects.
The other alternative is to make a ViewModel object and inject it in the XML in the onCreate of your Activity and then continue to call back and forth from the activity to the viewmodel for handling actions and lifecycles and feel free to manage that nightmare haha, I did an entire project this way and by the end of it, I redid it all to avoid all the duplication of coding efforts and hideous back and forths.
Goodluck and I hope that helps.
A very good question, and it is not as simple as it seems!
You can see an example from Google team here.
They solved the problem with the help of the factory.
There it is pass (of course) the Application context (not Activity context !).
A small problem - and so much boilerplate code!
My decision:
public class MainApplication extends Application {
public void onCreate() {
AppSharedPref sharedPref = AppSharedPref.getInstance(PreferenceManager.getDefaultSharedPreferences(this));
AppRepository.getInstance(sharedPref);
Repository is singltone (a lot of code is skipped for brevity):
public class AppRepository implements AppDataSource {
public static AppRepository getInstance(#NonNull AppSharedPref sharedPref) {
if (INSTANCE == null) {
INSTANCE = new AppRepository(sharedPref);
}
return INSTANCE;
}
In ViewModel call:
public class MyViewModel extends AndroidViewModel {
// constructor
public MyViewModel(#NonNull Application application) {
repository = AppRepository.getInstance(.....);
}
Look into Dagger 2!
That's true , you definitively shouldn't pass Activity to your xml or ViewModel. It will make your ViewModel no better than these 2000-line activities that we are trying to move away from with this architecture.
The solution we have in our MVVM project is to inject SharedPreferences with Dagger. You can of corse use ApplicationContext as well but do you need multiple instances of SharedPreferences in the project??
We a have a utility class for SharedPreferences and it is nice to keep it a singleton and inject wherever you need it.
I use MVVM in my application. I always try not to use Context inside my View Model. I also encountered the problem with SharedPreferences requiring a context to access the preference files. One of my solutions without using Dagger is to create a Preference utility class that will have reference to the application context. You initialize this utility class in you Application class. You get reference to the shared preference through a public static method provided by the utility class. You can directly call the utility class from your repository class. I prefer to contain all logic related to data storage in the repository class that's why i call the sharedpreference utility class in my repository class.
PreferenceManager.java
public class PreferenceManager {
private static SharedPreferences mSharedpreferences;
private PreferenceManager() {}
public static void initialize(Context context) {
mSharedpreferences= context.getSharedPreferences(context.getPackageName(),
Context.MODE_PRIVATE);
}
public static SharedPreferences getSharedPreferences() {
return mSharedpreferences;
}
}
App.java
public class App extends Application {
#Override
public void onCreate() {
PreferenceManager.initialize(this);
}
}
Repository.java
public class Repository {
public void someMethod() {
PreferenceManager.getSharedPreferences.edit.putBoolean("sample", true).apply();
}
You should use AndroidViewModel() in the ViewModel, pass application:Applicatoin, and use getApplication() to get the context.
ViewModel Example:
class MainTrendsViewModel (application: Application) : AndroidViewModel(application) {
// ViewModel must extend AndroidViewModel(), and pass application to it.
// Code here and
// use getApplication() to get context
}
Other anwer that work for me that you could reference: reference answer that works for me
You should use AndroidViewModel class or keep reference to Application context in yours ViewModel implementation in this case.
ViewModel class was designed to keep data persistent between different instances of Activity through its lifecircle and storing reference to one of Activity instance context really doesn't make sense.

Dagger 2 - how to avoid code repetition for injecting dependencies that require activity context

The project I'm working on has a number of utility classes that require activity context.
I don't want to have to declare a new #Provides method for each activity that uses the dependency. i.e. I don't want this:
#Provides
static Navigator providesNavigator(ActivityOne activity) {
returns new Navigator(activity);
}
// ...and in another module
#Provides
static Navigator providesNavigator(ActivityTwo activity) {
returns new Navigator(activity);
}
So instead I declare these utilities in a single ActivityUtilitiesModule and pass our BaseActivity which all other activities extend. Now i don't have to declare my Navigator dependency x number of times.
#Provides
static Navigator(BaseActivity activity) {
return new Navigator(activity);
}
However, Dagger does not know how to satisfy the dependency for BaseActivity. This means for every Activity i need to create a provides method that will satisfy the BaseActivity dependency with the specific Activity being used. e.g.:
#Provides
static BaseActivity providesBaseActivity(ActivityOne activity) {
return activity;
}
This is better - I only need to repeat this one provider per activity, rather than repeating a provider for every utility class per activity, but it still feels like an unwelcome additional step in Dagger set up, and another thing that makes the code harder to understand.
Is there a pattern which allows me to avoid having to supply this BaseActivity provider per activity?
Please use Constructor Injection. Having provide* methods that only call the constructor are only noise and code to maintain. Add #Inject to the class constructor and possible scopes onto the class.
#SomePossibleScope
class Navigator {
#Inject
Navigator(Activity activity) { }
}
If you do this, you probably don't need your ActivityUtilitiesModule at all.
If your class depends on an Activity or BaseActivity then you need to provide it. And yes, you will have to tell Dagger about it in some way.
If you were to use an abstract class or interface you should make use of #Binds instead.
#Binds BaseActivity bindsBaseActivity(ActivityOne activity);
Compared to #Provides Dagger might optimize this code further, reducing the number of method calls and object creations, as well as a few less lines of code.
I don't know why your Utils depend on the Activity, but if they would only need a Context then you could also just provide the application context to them without a need to bind or provide your actual Activity.
I personally just bind the current Activity to the types it implements using the syntax above. And if you're using Constructor Injection properly that's more often than not the only lines of code that you'll find in my modules, making them very readable.

Injecting mock presenters using Dagger2

My goal is to write instrumentation tests where the class under test is an Activity which has a mock presenter injected into it. I'd also like the presenter to have the same life as the activity that holds it. Finally, the mocks presenter that gets injected in the activity should also be able to be referenced from the test class so that the mock can be setup, verified etc... as part of the test.
Project setup:
I'm using gradle flavors to break the project into source sets that can be used for the different types of tests I'm trying to write. I have a mockRepo flavor where I have Dagger components and modules that create a "real" instance of all of my dependencies except for my repositories which I mock. I have an endToEnd flavor where I inject real instances of every dependency. The last flavor I'm attempting to add is a mockPresenter flavor which creates mock instances of the presenters so that I can truly isolate my views and ensure that when an activity's lifecycle methods run that the correct methods are called on the presenter.
The mockRepo and endToEnd flavors were pretty straightforward to write because in both cases I was able to extend the application class for testing and was able to swap out different dagger components in the application class which made it very easy to inject a mock repository.
The mockPresenter flavor is giving me problems. The issue is that I'm unable to inject a mock presenter into MainActivity without adding a method like
DaggerMainComponent getMainComponent() {
return mDaggerMainComponent
}
to my application class. I'd prefer not to do that because it seems like the application class shouldn't need to know about DaggerMainComponent at all and it's just a workaround.
Here's how the injection code for MainActivity currently looks:
#Inject
MainContract.Presenter mMainPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainComponent = DaggerMainComponent
.builder()
.appInjector(((MyApplication) getApplicationContext()).getAppComponent())
.mainModule(new MainModule())
.mainPresenterModule(new MainPresenterModule())
.build();
mMainComponent.inject(this);
mMainPresenter.setView(this);
}
What I like about doing things this way is that in onCreate I used the Dagger generated class called DaggerMainComponent to create an instance of component which guarantees that I will get a new Component which guarantees that I will get a new presenter every time onCreate runs. Also, I can get a reference to the component in onCreate and dereference it in onDestroy(). However, it also seems that it isn't possible to inject a mock MainPresenter because the only chance I have to do that is this here:
.mainPresenterModule(new MainPresenterModule())
MainPresenterModule only creates "real" instances of the presenter and if I were so use something like:
.mainPresenterModule(new MockPresenterModule())
then there would be no way to use a "real" version of the presenter for the production version of the app.
The workarounds that I've seen for this situation all seem to involve having a method on the application class that either return a component or a module. In the production version of the app the application class would return either a component that depends on modules that provide real instances or could even just supply the module itself. The test version of the app would have a test application that would extend the production application class and override some of the methods so when the test application was running it would return either the mock version of the component which would declare modules that would supply mocks or it would return the mock modules directly.
The other workaround I've seen uses an #ExposedForTesting annotation in the application class which seems like something I'd like to avoid.
Having the application class expose getter methods so that mock / real dependencies can be injected seems like a code smell to me because I can't see a real reason that the application class should know about the dependencies that should be injected into MainActivity. Also, it seems like you'd end up with one getter method per Activity or Fragment which would start to bloat the application class.
Is there a way to inject mocks into an Activity so that the application class doesn't play such a big part in providing the correct modules or components?

Dagger: need help in understanding

I have some misunderstandings of the way that dagger works:
There are only two ways to satisfy dependency: whether the #Provide method returns the instance, or the class should have #Singleton annotation, is that right? Must the class constructor have #Inject annotation in the latter case?
As I see, the ObjectGraph generates all the injection stuff. And it's said, that its inject(T instance) should be called to inject fields. However, I can just annotate my field with #Inject and it goes (field's class is #Singletone). ObjectGraph is not needed to satisfy such a dependency, right?
What about injects{} in #Module, what specifically does it give? Plz, provide an example of benefit when you keep all the injectable classes list.
Yes, there are two ways: #Provide methods in modules and #Singleton classes with #Inject at constructor.
Must the class constructor have #Inject annotation in the latter case?
Yes, otherwise object wouldn't be created by Dagger.
I don't think #Singleton with field injection could work. Because #Singleton at class with constructor injection means Dagger is responsible to keep one instance of this class. And it can create this class using constructor injection if all dependencies are satisfied. However, #Singleton with field injection seems misuse to me, cause keeping single instance of this class is user's responsibility now. Dagger can't instantiate this object itself.
Are you sure this configuration compiles and runs? And if it is check #Inject fields, they should be null by my understanding.
injects={} in #Module returns set of classes passed to ObjectGraph.inject(T class) or ObjectGraph.get(Class<T> class). Referring documentation:
It is an error to call ObjectGraph.get(java.lang.Class) or ObjectGraph.inject(T) with a type that isn't listed in the injects set for any of the object graph's modules. Making such a call will trigger an IllegalArgumentException at runtime.
This set helps Dagger to perform static analysis to detects errors and unsatisfied dependencies.
You can find some examples in this thread.

Categories

Resources