Can any one suggest a proper order to define a custom annotation in JAVA(Android). So that if I annotate a method with #Background annotation, the method should work on background thread.
This might be of use for your need case Creating custom Annotations. It seems like you would need to do #Retention(RetentionPolicy.RUNTIME) and #Target(ElementType.METHOD) scope to achieve what you want. Then as you can see in the first example, you would go into the object and etc.
For a good example, look at what they do in Dagger
As a final note, this is old and you've probably designed what you wanted, but it probably isn't a good idea to do what you asked. There is cost to annotation usage and Runnable was built basically for what you seem to be trying to do.
Android's Annotation subtypes provide a wide variety of tools for what you are trying to do. In particular, take a look at the thread annotations; I suspect that the #WorkerThread annotation does just what you want. The code inspection tools in Android Studio recognize these annotations and will automatically flag any code that it recognizes as violating the threading requirements (e.g., calling a UI thread method from a method annotated as #WorkerThread).
The code inspection tools also allow you to define your own annotations, but these are somewhat limited in what they can do. This is discussed in the section Creating Enumerated Annotations.
You can't use a custom annotation in JAVA(Android), because the android compiler doesn't support it. But maybe the follwing site can be helpful for you: http://androidannotations.org/
Related
It looks like we don't need to use kapt for #OnLifecycleEvent annotations to work. So, how do they get hooked up? Is it some kind of runtime annotation processing?
I'm asking because I'm curious what are the costs of using these annotations. Is using them affects application startup time? Or project compile time?
They are using reflection to find annotated functions with #OnLifecycleEvent. This is the real need why classes should implement LifecycleObserver. If there was kapt to do, that probably there shouldn't have been any interface to implement.
The resolution is on runtime, since the retention is set to RetentionPolicy.RUNTIME.
Reflection is expensive and therefore they are building static cache of each methods and uses the method reference, yes still reflection, to invoke each of them. I have no figures to provide how directly it affects the start up time.
I am currently integrating architecture components into my app according to the official documentation and the sample apps provided by google (sunflower and todo-app). I realized that none of these use interfaces for ViewModels (the sunflower app does not even use interfaces for repositories).
My question is: is it reasonable to just omit the interfaces for ViewModels (including advantages and disadvantages)?
Is it reasonable to just omit the interfaces for ViewModels?
The below is quite general and applicable not just for ViewModels.
Advantages:
less code
Disadvantages:
won't be able to use most of the well-known design patterns;
won't be able to properly unit test classes (no mocking);
won't be able to properly use dependency injection frameworks;
code refactoring when using another concrete implementation.
The answer depends on the complexity of your ViewModel. If you are never going to create more than one implementation of an interface (including mocking), then there is no need to create the interface, so you can reduce the code and the overall maintenance burden.
That said the important things to consider are:
Can you unit test your view model, even without the interface (answer should be yes, otherwise you have some other problems IMO)
Can you still use a dependency injection framework (the answer is yes at least for some DI frameworks like Prism)
Are you only ever going to create one implementation of your ViewModel?
I believe that the mark of a well-designed ViewModel, should have a relatively simple implementation, and be easy to unit-test without having to resort to mocking.
I want to understand what is happening behind the scenes in a RoomDatabase, that it requires the DAO to be either an interface or an abstract class.
I've been searching for quite a while, but all articles and documentation only explain the how, not the why.
It is not just the Room, Retrofit and other libraries use this pattern too, it is called Programming to an Interface.
Instead of just creating a concrete implementation you just specify the stuff you want to do and they provide you with an implementation that will behave as you requested.
For further study you can check this article:
https://tuhrig.de/programming-to-an-interface/
The data access object, or Dao, is an annotated class where you specify SQL queries and associate them with method calls.
The DAO must be an interface or abstract class because we want to make sure that the CRUD methods we will be creating inside it are implemented at the Class level. Which is actually the whole idea of having an interface or abstract class.
Mr. #keivan-esbati is correct about the principle, but I believe he is omitting an important fact about Room DAO.
Not everything can be programmed to an interface. Especially systems whose behaviors cannot be accurately predefined.
And this lack of specificity is the absolute case of Database queries. The difference here is that Room, with the help of the IDE, offers a type of code auto generation.
Without this plugin that inspects strings at build time, it would be nearly impossible to encapsulate the functionality of a DAO inside an interface/abstract..., it could be done..., but it would be relegated to the most basic functionality.
In this case the interface is not used for the same goal as the design principle..., the principle is instead used as a vehicle that the plugin uses for code generation, but the end goal is to allow the plugin to autogenerate code.
While the design principle's goal is to keep the application's memory footprint in check, prevent redundancies and a couple of other outcomes (like separation of concerns (the link mr. Keivan posted talks about this)) that inevitably result in "the path of least resistance", the code autogenerated by the plugin may actually have the opposite effect.
Code coverage (Jacoco) in Android connected tests is a very useful way to determine what methods/functions need some TLC. Now that I am switching to Kotlin over Java I have discovered some anomalies that I cannot explain, as this screen shot illustrates:
The methods starting with _$... are internal to Kotlin or Android, I strongly suspect. My questions are: 1) does anyone have any insight into why these methods are included in the Jacoco code coverage report, and 2) is there a way to exclude them?
Those methods are added when using the synthetic properties via Kotlin Android Extensions. Each Kotlin Activity using synthetic properties will have those methods added.
Kotlin Android Extensions is a plugin for the Kotlin compiler, and it does two things:
Adds a hidden caching function and a field inside each Kotlin Activity. The method is pretty small so it doesn't increase the size of APK much.
Replaces each synthetic property call with a function call.
Explanation on the official docs:
https://kotlinlang.org/docs/tutorials/android-plugin.html#under-the-hood
This articles does a pretty good job going into detail:
https://antonioleiva.com/kotlin-android-extensions/
In large part due to the answer from #triad, I was able to come up with a solution that is a work-around to what appears to be a Kotlin bug. The work-around was documented in the Antonio Leiva post referenced by #triad. In a nutshell the solution was to turn off caching in MainActivity. The complete solution is up on GitHub.
What I do not completely understand is the cost of this solution so I will hold off checking this answer in the hopes that a better solution is provided.
I am evaluating Dependency Injection (DI) frameworks for an Android app. The top contenders are: Dagger (with Butter Knife) and Android Annotations. I understand that Dagger and ButterKnife are from the same source- square and they complement each other. Here're are the key matrices that I am looking for:
Ease of use (our build is based on Gradle and we use Android Studio IDE)
Testing support (we use Robotium for functional testing and RoboLectric for unit testing)
Performance (DI frameworks use reflection, which one is faster?)
AndroidAnnotations
uses compile time annotation processing. It generates a sub class with an underscore apppended to the original name (MyActivity_ generated from MyActivity). So to have it work you always have to use the generated class for references instead of your original class.
It has a very rich feature set, see the list of available annotations.
Butterknife
uses also compile time annotation processing, but it generates finder classes which are used by a central class (ButterKnife). This means that you can use your original class for referencing, but you have to call the injection manually. A copy from the ButterKnife introduction:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.inject(this);
// TODO Use "injected" views...
}
The feature set is not so rich, ButterKnife supports view injection (AndroidAnnotations equivalent would be #ViewByIdand #ViewsById) and some event binding (for a complete list see the namespace directory here, just count the OnXXX event annotations).
Dagger
is a DI implementation for Android, similar to Guice. It also uses compile time annotation processing and generates object graphs which you use for manually injection. You distinguish between application object graph and scoped object graphs for injecting e.g. in activities. Here you see an Application.onCreate example:
#Override public void onCreate() {
super.onCreate();
objectGraph = ObjectGraph.create(getModules().toArray());
objectGraph.inject(this);
// use injected classes
}
I found it is harder to start with dagger, but this might be only my experience. However see some videos here for a better start: 1, 2
From the feature set point of view I would say that Dagger implements functionalities which could be compared to AndroidAnnotation's #EBean and #Bean functionality.
Summary
If you are comparing ease of use, testing support and performance I can't find much difference between using AndroidAnnotation and ButterKnife+Dagger. Differences are in the programming model (use classes with _ instead of using the original ones and call the injection manually) and in the feature set.
AndroidAnnotation gives you a full list of functionalities, but ties you to certain libraries. For example if you use it's rest api you have to use Spring Android. You also have annotations for features like OrmLite (#OrmLiteDao) regardless if you use OrmLite or not.
At the end it is a matter of taste, at least in my opinion.
Here is the Nice article in Dzone blog.
We to need to compare the features of each, such as :
Minimum Jars required
ActionBarSherlock compatibility
Injection for click listeners
POJO injection
Performance
Only Pojo Injection missing in butterknife! So looks like Butterknife is the winner!
Source
Google does ask specifically not to use dependency injection.
But by reading their request they seem to be referring more to the Guice and reflection based DI library's. Libraries such as android annotation use no reflection instead employing compile time generated code, while butterknife and dagger uses a small amount of reflection optimised for android but are supposedly slightly more powerful than android annotation. It really depends on the project and how much of a performance hit you are willing to take. In my opinion just using butterknife is sufficient to speed up code development by itself. If you need slightly more use android annotation and lastly if you are willing to take a slight performance hit due to reflection the best option without absolutely destroying performance with a powerhouse Guice based reflection use dagger + butterknife.
You should give a try at Toothpick.
Toothpick is (per the README):
pure java
fast, it doesn't use reflection but annotation processing
simple, flexible, extensible & powerful, robust & tested
thread safe
documented & Open Source
scope safe : it enforces leak free apps
test oriented : it makes tests easier
it works very well with Android or any other context based framework (such as web containers)
It can even be faster than Dagger 2 in most cases, and it's much simpler.
Note: Yes, I am one of the authors.
Use Android Annotations or Butterknife to ease your coding. But don't go for Roboguice! Roboguice forces your activies, fragments to extend to roboguice classes. Not fun, at all!
Dagger 2 is a much better option. You can use it along with Android Annotations if you'd like. I would just use Android Annotations for a simple app, but these days is good to work more with Dagger.
Seems like Google chooses dagger, as they are developing it jointly with Square, who created it.
Concerning Butterknife and Dagger themselves, there is the SO question difference-between-dagger-and-butterknife-android which clarifies how they complement each other.
The reddit-thread mentioned by #ChrLipp has someone who used all three on the same project, speaks highly of dagger+butterknife but also gives AndroidAnnotations its place:
For dependency injection, butterknife is used for Views, Dagger is
used for all objects and is highly recommended and Android Annotations
creates more of a framework for developing Android instead of
injecting objects into your classes so each library are quite
different from each other. Dagger is equivalent to Guice but is much
much faster. Dagger is more powerful then ButterKnife and Android
Annotations as it injects all objects rather than ButterKnife and
Android Annotations which only inject a certain set of objects.
Dagger can be a pain to setup and configure but is well worth it once
you have it done. But then again, because these are all quite
different from each other, it all depends on what your needs are for
the project.
Also, speaking of each one being quite different, in your project you
can use ButterKnife, Android Annotations and Dagger all in the same
project if you really want to. They each have the same idea but do
something different so you could use them all.
Eventually if you use one of the three, you'll have a hard time transitioning to Android's databinding. That's what's fastest if you need to consider performance:
https://developer.android.com/tools/data-binding/guide.html