Skip to content

Instantly share code, notes, and snippets.

@donnfelker
Created January 22, 2016 17:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donnfelker/a54b3e37c6a9fc7775ac to your computer and use it in GitHub Desktop.
Save donnfelker/a54b3e37c6a9fc7775ac to your computer and use it in GitHub Desktop.
Dagger Part 1 Examples
@Singleton
@Component(modules = { ApplicationModule.class, ApiModule.class })
public interface ApplicationComponent {
void inject(TaskoApplication target);
void inject(MainActivity target);
}
@Module
public class ApplicationModule {
private Application application;
public ApplicationModule(Application application) {
this.application = application;
}
@Provides @Singleton
public Context provideContext() {
return application;
}
@Provides @Singleton
public SharedPreferences provideSharedPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
public class MainActivity extends AppCompatActivity {
@Inject SharedPreferences prefs;
private FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((TaskoApplication)getApplication()).getComponent().inject(this);
if(prefs != null) {
Log.d("Dagger2", "Prefs is not null");
}
//.. rest of it left out for brevity ...
}
}
public abstract class TaskoApplication extends Application {
private ApplicationComponent component;
@Override
public void onCreate() {
super.onCreate();
component = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
// Configure Realm for the application
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name("tasko.realm")
.build();
Realm.deleteRealm(realmConfiguration); // Clean slate
Realm.setDefaultConfiguration(realmConfiguration); // Make this Realm the default
}
public ApplicationComponent getComponent() {
return component;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment