Tech Blogging‎ > ‎

Android and Dagger 2 in 5 minutes!

posted Aug 12, 2017, 12:59 AM by Haris Hashim   [ updated Aug 12, 2017, 1:27 AM ]

Introduction

Dagger 2 for Android can be unnecessarily complicated. Here is a tutorial for simplified usage of Dagger 2 as well as adding "quickstart" code as Android Studio Live Template.

Steps

Use Android Studio to create a new project.


Create new android project

Just click next and accept all the default option. Just make sure that it targets phone and tablet and MainActivity class is created by the wizard.

Add Dagger 2 dependency to gradle app module.

Add force resolution strategy


Add the following code as per above picture. These codes might not bee needed so feel free to try without it.

    
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}

And the needed dependency as per bellow picture.  

Add dagger dependencies


Use bellow codes to copy paste.

compile 'com.google.dagger:dagger:2.11'
compile 'com.google.dagger:dagger-android:2.11'
compile 'com.google.dagger:dagger-android-support:2.11'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'
annotationProcessor 'com.google.dagger:dagger-compiler:2.11'


Add quick start code to Live Templates

Use the file menu to open Settings => Editor => Live Templates

Life Template

Select "user" and add a new user Live Template as per bellow image. Set Abbreviation to something easily remembered. This example use "DA" as the shortcut, so that you can type DA and press TAB key to generate the code.

Create User Live Template

Use bellow code as the template by copy and paste into Template text.

public class App extends Application implements HasActivityInjector {

@Inject
DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;

@Override
public void onCreate() {
super.onCreate();
DaggerAppComponent.create().inject(this);
}

@Override
public DispatchingAndroidInjector<Activity> activityInjector() {
return dispatchingAndroidInjector;
}

//Move this interface to its own class file and do Build => Make Project
@Component(modules = { AndroidInjectionModule.class, AppModule.class})
public interface AppComponent extends AndroidInjector<App> {
}

@Module
public abstract class AppModule {
@ContributesAndroidInjector
abstract MainActivity mainActivity();
}
}


Create App Class and Set the Manifest

Add a class that extend Application class. This can be done by right clicking the application package and use context menu to add a new Java class. Refer to bellow pictures.

Right click on application package

Name the class App and superclass to be android.app.Application.

Add App class

Set the class as application class for the project app module.

Set the app in manifest

Use Live Template to Add Boilerplate Codes

Open the App class so that we can add codes saved earlier as Live Template. Just delete bellow code.



public class App extends Application {
}

Type abbreviation that we set previously; in this case DA and press TAB on the keyboard. You should get the code as bellow picture.

Generate Live Template code and resolve missing import

As in above picture, blue box will popup to resolve missing import. Just press ALT + ENTER until they are all resolved.

However DaggerAppComponent (line 14 in the picture) will not resolve. Dagger has to generate DaggerAppComponent class. For this to happen we need to move AppComponent interface to its own file.

To do this cut bellow codes from your App class.


//Move this interface to its own class file and do Build => Make Project
@Component(modules = {AndroidInjectionModule.class, AppModule.class})
public interface AppComponent extends AndroidInjector<App> {
}

Create a new interface and name it AppComponent. We will not need AppComponent code generated in this file. Simply delete and paste code that we cut in above step.

Use keyboard shortcut  CTRL+F9 to make the project. After make is completed, DaggerAppComponent in App class should be successfully resolved.

Create a TestService Class and Inject it to MainActivity for testing.

Use bellow code for TestService class. Take note of the @Inject decoration usage. TestService constructor will be called when it is injected into MainActivity class.



public class TestService {

private TestUser user;

@Inject
public TestService(){
user = new TestUser();
user.setName("Test User");
user.setEmail("test@user.com");
}

public TestUser getUser() {
return user;
}

public class TestUser {
private String name;

private String email;


public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}
}

Ensure that MainActivity layout file have the following TextView widget


<TextView
android:id="@+id/text_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />

And implement codes as in bellow picture in exact order as highlighted.

Main activity code

Bellow codes for copy paste.


public class MainActivity extends AppCompatActivity {

@Inject TestService testService;

@Override
protected void onCreate(Bundle savedInstanceState) {

AndroidInjection.inject(this);

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView textHello = (TextView)findViewById(R.id.text_hello);
if(testService != null){
textHello.setText("SUCCESS! User is " + testService.getUser().getName() +
" and email is " + testService.getUser().getEmail());
}else{
textHello.setText("FAILURE!");
}

}
}


If everything is done correctly, we will see bellow screenshot when the app is run.

Success screenshot


Conclusion

It takes 5 minutes or less to start using Dagger 2 when utilizing Android Studio Live Template functionality.

Much faster to just clone the code from https://github.com/HarisHashim/QuickDagger ;) . 

Thanks for reading and have fun!
Comments