What is Dagger Dependency?
If you are dagger dependency beginner please follow and understand very carefully. First, you add the dependency in your android studio gradle.
var dagger = '2.15'
implementation "com.google.dagger:dagger:$rootProject.dagger"implementation "com.google.dagger:dagger-android:$rootProject.dagger"implementation "com.google.dagger:dagger-android-support:$rootProject.dagger"annotationProcessor "com.google.dagger:dagger-compiler:$rootProject.dagger"annotationProcessor "com.google.dagger:dagger-android-processor:$rootProject.dagger"
Now you create a simple HelloData class and make one method name by sayHello().
public class HelloData { public String sayHello() { return "Hello android This is my first dagger app"; }
}
Now you create module name by AppModule
@Module
public class AppModule {
@ProvidesContext provideContext(App application) { return application.getApplicationContext(); } @Singleton@ProvidesHelloData helloData() { return new HelloData(); }
}
Create Component
@Singleton@Component(modules = {AppModule.class,AndroidInjectionModule.class}) public interface AppComponent { @Component.Builder interface Builder { @BindsInstance Builder application(Application application); AppComponent build(); } void inject(AppApplication aaApp);}
Create Custom Application class
public class AppApplication extends Application implements HasActivityInjector { private AppComponent appComponent; private static AppApplication appApplication; @Inject DispatchingAndroidInjector<Activity> activityDispatchingAndroidInjector; public static AppApplication getAppApplicationInsatnce() { return appApplication == null ? new AppApplication() : appApplication; } @Override public void onCreate() { super.onCreate(); DaggerAppComponent.builder().application(this).build().inject(this); } public AppComponent getAppComponent() { return appComponent; } @Override public AndroidInjector<Activity> activityInjector() { return activityDispatchingAndroidInjector; } }
Now finally create Activity class
public class MainActivity extends AppCompatActivity { @Inject HelloData helloData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidInjection.inject(this); setContentView(R.layout.activity_main); } @Override protected void onResume() { super.onResume(); Log.e("TAG"," Comming msg-2 "+ helloData.sayHello()); } }
Thank you
No comments:
Post a Comment