Dependency Injection Dagger 2 Basic Set Up for Android Project

The following steps are for setting up a very basic Dependency Injection setting using the framework Dagger 2 for Android Project. This setting only injects the SharedPreferences Object.

1. Add this classpath in the project build.gradle file

dependencies {
    // other classpath ...
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}

2. Add this line in the app build.gradle file after apply plugin: 'com.android.application'

apply plugin: 'com.neenbedankt.android-apt'

3. Add these 3 lines in the dependencies in the app build.gradle file

dependencies {
    apt 'com.google.dagger:dagger-compiler:2.7'
    compile 'com.google.dagger:dagger:2.7'
    provided 'javax.annotation:jsr250-api:1.0'
}

4. Create a package dagger.modules and create the class AppModule.java in it

@Module
public class AppModule {

    Application mApp;

    public AppModule(Application application) {
        mApp = application;
    }

    @Provides
    @Singleton
    Application providesApplication() {
        return mApp;
    }
}

5. Create another class PersistetModule.java in the package dagger.modules

@Module
public class PersistentModule {
    @Provides
    @Singleton
    // Application reference must come from AppModule.class
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }
}

6. Create a package dagger.components and create the interface PersistentComponent.java in it

@Singleton
@Component(modules={AppModule.class, PersistentModule.class})
public interface PersistentComponent {
    void inject(MainActivity activity);
}

7. Add the following into the Project Application class, for example, MyApp.java which should be defined as the name of the application tag in the manifest file.

public class MyApp extends Application {
    private PersistentComponent mPersistentComponent;
    @Override
    public void onCreate() {
        super.onCreate();
        mPersistentComponent = DaggerPersistentComponent.builder()
                .appModule(new AppModule(this))
                .persistentModule(new PersistentModule())
                .build();
    }

    public PersistentComponent getPersistentComponent() {
        return mPersistentComponent;
    }
}

8. Use it in the MainActivity

public class MainActivity extends Activity {
    @Inject
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ((MyApp) getApplication()).getPersistentComponent().inject(this);

        SharedPreferences.Editor ed = sharedPreferences.edit();
        ed.putString("key", "some text...");
        ed.commit();
    }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search