-
-
Save donnfelker/a54b3e37c6a9fc7775ac to your computer and use it in GitHub Desktop.
Dagger Part 1 Examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Singleton | |
@Component(modules = { ApplicationModule.class, ApiModule.class }) | |
public interface ApplicationComponent { | |
void inject(TaskoApplication target); | |
void inject(MainActivity target); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ... | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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