I'm using Dagger for DI and Retrofit for network.
When i trying to call retrofits api method in my presenter, i catchs NPE.
Here is Network module:
#Module
public class NetworkModule {
String baseUrl;
public NetworkModule(String baseUrl) {
this.baseUrl = baseUrl;
}
#Provides
#Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
return gsonBuilder.create();
}
#Provides
#Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(baseUrl)
.build();
}
#Provides
#Singleton
UsersApi provideUsersApi(Retrofit retrofit){
return retrofit.create(UsersApi.class);
}
}
And app component:
#Singleton
#Component(dependencies = {}, modules = {AppModule.class, DatabaseModule.class, NetworkModule.class})
public interface AppComponent {
void inject(UsersFragmentPresenter usersFragmentPresenter);
UserDao userDao();
Retrofit retrofit();
UsersApi usersApi();
AppDatabase appDatabase();
Application application();
}
And when i inject api and call api method here, the member isn't inizialized
#InjectViewState
public class UsersFragmentPresenter extends MvpPresenter<BaseFragmentView> {
#Inject
UsersApi usersApi; // is null
public UsersFragmentPresenter() {
App.getAppComponent().inject(this);
}
public void loadData(){
usersApi.getUser()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
Related
I I am using Android Dagger2 but I am getting the error like it
error: [dagger.android.AndroidInjector.inject(T)] android.app.Application cannot be provided without an #Inject constructor or from an #Provides-annotated method.
android.app.Application is injected at
com.nwrn.pfdy.DI.Module.AppModule.provideContext(application)
android.content.Context is injected at
com.nwrn.pfdy.DI.Module.AppModule.provideAppPreferencesHelper(context)
com.nwrn.pfdy.Data.Prefs.AppPreferencesHelper is injected at
com.nwrn.pfdy.DI.Module.NetworkModule.provideAddCookiesInterceptor(appPreferencesHelper)
com.nwrn.pfdy.Network.Cookies.AddCookiesInterceptor is injected at
com.nwrn.pfdy.DI.Module.NetworkModule.provideRetrofitService(addCookiesInterceptor, …)
com.nwrn.pfdy.Network.Retrofit.RetrofitService is injected at
com.nwrn.pfdy.View.Login.LoginActivityModule.provideLoginViewModel(retrofitService)
com.nwrn.pfdy.View.Login.LoginViewModel is injected at
com.nwrn.pfdy.View.Login.LoginActivity.mLoginViewModel
com.nwrn.pfdy.View.Login.LoginActivity is injected at
dagger.android.AndroidInjector.inject(arg0)
This is my AppComponent Code
#Singleton
#Component(modules = {AndroidInjectionModule.class, AppModule.class, ActivityModule.class, NetworkModule.class})
public interface AppComponent {
void inject(BaseApplication baseApplication);
#Component.Builder
interface Builder{
#BindsInstance
Builder application(BaseApplication baseApplication);
AppComponent build();
}
}
Below is My Code of Modules
#Module
public class AppModule {
#Provides
#Singleton
Context provideContext(Application application) {
return application;
}
#Provides
#Singleton
AppPreferencesHelper provideAppPreferencesHelper(Context context) {
return new AppPreferencesHelper(context);
}
}
this is another module
#Module
public class NetworkModule {
#Provides
AddCookiesInterceptor provideAddCookiesInterceptor(AppPreferencesHelper appPreferencesHelper) {
return new AddCookiesInterceptor(appPreferencesHelper);
}
#Provides
ReceivedCookiesInterceptor provideReceivedCookiesInterceptor(AppPreferencesHelper appPreferencesHelper) {
return new ReceivedCookiesInterceptor(appPreferencesHelper);
}
#Singleton
#Provides
RetrofitService provideRetrofitService(AddCookiesInterceptor addCookiesInterceptor, ReceivedCookiesInterceptor receivedCookiesInterceptor) {
return new RetrofitClient(addCookiesInterceptor, receivedCookiesInterceptor).getService();
}
}
Below code is About Injection Class
public class RetrofitClient {
private RetrofitService service;
private static final String baseURL = "http://192.168.0.33:8070/";
public RetrofitClient(AddCookiesInterceptor addCookiesInterceptor, ReceivedCookiesInterceptor receivedCookiesInterceptor) {
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
client.interceptors().add(addCookiesInterceptor);
client.interceptors().add(receivedCookiesInterceptor);
Retrofit retrofit = new Retrofit.Builder().baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
service = retrofit.create(RetrofitService.class);
}
public RetrofitService getService() {
return service;
}
}
public class AddCookiesInterceptor implements Interceptor {
private AppPreferencesHelper mAppPreferencesHelper;
public AddCookiesInterceptor(AppPreferencesHelper appPreferencesHelper){
this.mAppPreferencesHelper = appPreferencesHelper;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
Set<String> preferences = mAppPreferencesHelper.getCookie();
for (String cookie : preferences) {
builder.addHeader("Cookie", cookie);
}
// Web,Android,iOS 구분을 위해 User-Agent 세팅
builder.removeHeader("User-Agent").addHeader("User-Agent", "Android");
return chain.proceed(builder.build());
}
}
public class ReceivedCookiesInterceptor implements Interceptor {
private AppPreferencesHelper mAppPreferencesHelper;
public ReceivedCookiesInterceptor(AppPreferencesHelper appPreferencesHelper)
{
this.mAppPreferencesHelper = appPreferencesHelper;
}
#Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
HashSet<String> cookies = new HashSet<>(originalResponse.headers("Set-Cookie"));
// Preference에 cookies를 넣어주는 작업을 수행
mAppPreferencesHelper.setCookie(cookies);
}
return originalResponse;
}
}
public class AppPreferencesHelper implements PreferencesHelper {
private static final String PREF_KEY_COOKIE_NAME = "PREF_KEY_COOKIE_NAME";
private final SharedPreferences mPrefs;
public AppPreferencesHelper(Context context) {
mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
#Override
public Set<String> getCookie() {
return mPrefs.getStringSet(PREF_KEY_COOKIE_NAME, new HashSet<String>());
}
#Override
public void setCookie(HashSet<String> cookie) {
mPrefs.edit().putStringSet(PREF_KEY_COOKIE_NAME, cookie);
}
}
public interface PreferencesHelper {
Set<String> getCookie();
void setCookie(HashSet<String> cookie);
}
Injection Flow is like this
Rerofit2 => AddCookiesInterceptor, ReceivedCookiesInterceptr => AppPreferencesHelper => Context
what i got about this error by testing is that error is caused by provideContext in AppModule.
if i change AppPreferencesHelper Constructor without parameter like this (without provideContext) it doesn't make an error
public AppConstructor(){
}
and
#Module
public class AppModule {
#Provides
#Singleton
Context provideContext(Application application) {
return application;
}
#Provides
#Singleton
AppPreferencesHelper provideAppPreferencesHelper() {
return new AppPreferencesHelper();
}
}
Many thanks for any suggestions
Edited
Seems like you need to change Application to BaseApplication at provideContext method.
Hope this helps!
I want to know how to inject Presenter in activity using code Following are details
Following is error message:
Error:(12, 46) error: cannot find symbol class DaggerCategoryPresenterComponent
Error:(9, 46) error: cannot find symbol class DaggerNetComponent
Error:(18, 10) error: [Dagger/MissingBinding] com.headytest.android.category_listing.CategoryContract.CategoryPresenter cannot be provided without an #Provides-annotated method.
com.headytest.android.category_listing.CategoryContract.CategoryPresenter is injected at
com.headytest.android.MainActivity.categoryPresenter
com.headytest.android.MainActivity is injected at
com.headytest.android.dagger_component.NetComponent.inject(com.headytest.android.MainActivity)
Following are modules
#Module
public class NetworkModule {
String baseURL;
public NetworkModule(String baseURL) {
this.baseURL = baseURL;
}
#Provides
#Singleton
Cache provideHttpCache(Application application) {
int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(application.getCacheDir(), cacheSize);
return cache;
}
#Provides
#Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
#Provides
#Singleton
OkHttpClient provideOkhttpClient(Cache cache) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.cache(cache);
client.addInterceptor(interceptor);
return client.build();
}
#Provides
#Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
try {
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(baseURL)
.client(okHttpClient)
.build();
} catch (Exception e) {
e.printStackTrace();
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(Constants.BASE_URL)
.client(okHttpClient)
.build();
}
}
}
ApplicationModule
#Module
public class ApplicationModule {
Application application;
public ApplicationModule(Application application) {
this.application = application;
}
#Provides
#Singleton
Application providesApplication() {
return application;
}
}
CategoryContractModule
#Module
public class CategoryContractModule {
public CategoryContractModule() {
}
#Provides
#AScope
CategoryContract.CategoryPresenter providesCategoryPresenter(CategoryPresenterImpl categoryPresenter) {
return (CategoryContract.CategoryPresenter)categoryPresenter;
}
}
Following are components:
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetComponent {
void inject(MainActivity activity);
}
CategoryPresenterComponent:
#AScope
#Component(dependencies = NetComponent.class, modules =
{CategoryContractModule.class})
public interface CategoryPresenterComponent {
void inject(MainActivity activity);
}
AScope
#Scope
#Retention(RetentionPolicy.RUNTIME)
public #interface AScope {
}
Following is the code in MainActivity:
#Inject
CategoryPresenter categoryPresenter;
#Inject
Retrofit retrofit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerCategoryPresenterComponent.builder()
.categoryContractModule(new CategoryContractModule())
.netComponent(((App) getApplicationContext()).getNetComponent())
.build()
.inject(this);
}
CategoryPresenterImpl
public class CategoryPresenterImpl implements CategoryContract.CategoryPresenter {
#Inject
public CategoryPresenterImpl() {
}
#Override
public void onStart() {
}
#Override
public void onStop() {
}
#Override
public void getCategoryLiast() {
}
}
I assume current error will be easy to fix, because it very much looks like this issue.
You've instructed Dagger how to provide #AScope CategoryContract.CategoryPresenter but in activity you request Dagger to inject CategoryContract.CategoryPresenter. Dagger is confused at this point, because those two things do not match.
What you have to do, is simply add #AScope to categoryPresenter:
#Inject
#AScope
CategoryPresenter categoryPresenter;
I've checked out your project. The problem was in NetComponent.java:
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetComponent {
void inject(MainActivity activity);
}
The issue is in line void inject(MainActivity activity). Why is this an issue? Because by the time you construct NetComponent in App, dagger analyzes MainActivity for #Inject annotated field and sees CategoryPresenter. This means, that at this point Dagger should find appropriate provider/binder method in order to be able to inject MainActivity as declared inside this interface.
But it cannot find such a provider/binder method, because it is declared in an another component - CategoryPresenterComponent and this component (NetComponent) is not connected with CategoryPresenterComponent anyhow (subcomponents or component dependencies), thus bindings are not exposed.
Simply removing that line will make your build successful:
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetComponent {
}
For resolving "Error:cannot access Nullable" refer to this thread, which suggest applying compile 'com.google.code.findbugs:jsr305:3.0.2' to your gradle file.
After doing this you'll overcome that error message and will stumble on retrofit2.Retrofit cannot be provided without an #Inject constructor or an #Provides-annotated method, which has the same symptoms as CategoryPresenter had.
To overcome this issue you have to add a Retrofit provider method inside NetComponent (or to remove #Inject Retrofit retrofit from activity):
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetComponent {
Retrofit providesRetrofit();
}
After doing this you'll be able to run the app, but you'll end up in a NPE in MainActivity, because of this line:
.categoryContractModule(new CategoryContractModule(retrofit.create(HeadyAPI.class)))
You are referring to retrofit object, which is not yet initialized.
Long story short, your initial question has mutated a couple of times and in fact you had a few problems in your code. Still you have a problem there, because you are trying to use retrofit in order to construct a component, that was supposed to inject the retrofit for you.
I have a LoginActivity where the user logs in via Auth0 and returns an auth token. This token is passed to MainActivity:
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(KEY_ACCESS_TOKEN, credentials.getAccessToken());
intent.putExtra(KEY_ID_TOKEN, credentials.getIdToken());
startActivity(intent);
I was able to get dependency injection working with LoginActivity fine by following this guide.
Now I'm trying to inject dependencies into MainActivity. My MainActivity has a MainActivityViewModel to handle all the interactions between the UI and the data layer. I'd like to inject my API into my ViewModel:
PetshackApi apiService;
#Inject
public PetMapViewModel(PetshackApi apiService) {
this.apiService = apiService;
}
I have ViewModelModule, ViewModelKey, and MainActivityViewModelFactory (renamed from GithubViewModelFactory) defined. I injected the viewModelFactory at the top of my MainActivity:
#Inject
ViewModelProvider.Factory viewModelFactory;
And then use the factory to get my viewModel:
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainActivityViewModel.class);
I set this up using this answer.
The problem is that my Retrofit/PetshackApi dependency will require the accessToken from the LoginActivity. So I defined another method in my MainActivity to allow retrieving it:
public String getAccessToken() {
return getIntent().getStringExtra(LoginActivity.KEY_ACCESS_TOKEN);
}
I'm having trouble setting up my modules/components/???. I think I need to inject MainActivity somehow into my modules so I tried following Injecting Activity objects.
MainActivityComponent.java
#Component(modules={AndroidSupportInjectionModule.class, AppModule.class, MainActivityModule.class, ViewModelModule.class})
public interface MainActivityComponent extends AndroidInjector<PetApplication> {
#Component.Builder
abstract class Builder extends AndroidInjector.Builder<PetApplication>{
#BindsInstance
abstract Builder application(Application application);
}
void inject(MainActivity mainActivity);
}
MainActivityModule.java
#Module(subcomponents = MainActivitySubcomponent.class)
abstract class MainActivityModule {
#Binds
#IntoMap
#ActivityKey(MainActivity.class)
abstract AndroidInjector.Factory<? extends Activity>
bindMainActivityInjectorFactory(MainActivitySubcomponent.Builder builder);
}
MainActivitySubcomponent.java
#Subcomponent(modules = MainActivityChildModule.class)
public interface MainActivitySubcomponent extends AndroidInjector<MainActivity> {
#Subcomponent.Builder
public abstract class Builder extends AndroidInjector.Builder<MainActivity> {}
}
MainActivityChildModule.java
#Module
abstract class MainActivityChildModule {
#Provides
#Singleton
Retrofit providesRetrofit(Application application, MainActivity mainActivity) {
final String accessToken = mainActivity.getAccessToken();
Interceptor interceptor = new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("authorization", "Bearer " + accessToken).build();
return chain.proceed(newRequest);
}
};
// Add the interceptor to OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
OkHttpClient client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(application.getString(R.string.endpoint_url))
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
#Provides
#Singleton // needs to be consistent with the component scope
PetshackApi providesPetshackApiInterface(Retrofit retrofit) {
return retrofit.create(PetshackApi.class);
}
}
Am I on the right track? Any hints or examples on how to do this?
I'd recommend moving your networking code outside of your Activity module and creating an Application module that could be shared across your application.
The important thing is, if you have a TokenStore that provides your token for each request you'd need to update the value as requests are sent.
#Module
abstract class NetworkModule {
#Provides
#Singleton
static TokenStore provideTokenStore(TokenStoreImpl tokenStore) {
return tokenStore;
}
#Provides
#Singleton
static OkHttpClient provideOkHttpClient(AuthInterceptor authInterceptor) {
// Add the interceptor to OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(authInterceptor);
return builder.build();
}
#Provides
#Singleton
static Retrofit providesRetrofit(Application application, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(application.getString(R.string.endpoint_url))
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
#Provides
#Singleton // needs to be consistent with the component scope
static PetshackApi providesPetshackApiInterface(Retrofit retrofit) {
return retrofit.create(PetshackApi.class);
}
}
interface TokenStore {
String getToken();
void setToken(String token);
}
#Singleton
class TokenStoreImpl implements TokenStore {
String token;
#Inject
public TokenStoreImpl() { }
#Override
public String getToken() {
return token;
}
#Override
public void setToken(String token) {
this.token = token;
}
}
#Singleton
class AuthInterceptor implements Interceptor {
private final TokenStore tokenStore;
#Inject
public AuthInterceptor(TokenStore tokenStore) {
this.tokenStore = tokenStore;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request()
.newBuilder().addHeader("authorization", "Bearer " + tokenStore.getToken()).build();
return chain.proceed(newRequest);
}
}
I am using dagger2 in my application. I have created module, component which is being in my entire application so I am initializing it in the application class.
Below is my module, component of dagger2 which are helping for resolving dependencies.
NetComponent.java
#Singleton
#Component(modules = {AppModule.class, NetModule.class})
public interface NetComponent {
void inject(AuthenticationActivity authenticationActivity);
void inject(PaymentActivity paymentActivity);
}
AppModule.java
#Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
#Provides
#Singleton
Application providesApplication() {
return application;
}
}
NetModule.java
#Module
public class NetModule {
#Provides
#Singleton
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}
#Provides
#Singleton
Cache provideOkHttpCache(Application application) {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(application.getCacheDir(), cacheSize);
return cache;
}
#Provides
#Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newBuilder()
//.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.cache(cache)
.build();
return okHttpClient;
}
#Provides
#Singleton
#Named("authRetrofit")
Retrofit provideAuthRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(PAYMENT_SERVICE)
.client(okHttpClient)
.build();
return retrofit;
}
#Provides
#Singleton
#Named("paymentRetrofit")
Retrofit providePaymentRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(LOGIN_SERVICE)
.client(okHttpClient)
.build();
return retrofit;
}
}
AppApplication.java
public class AppApplication extends Application {
private NetComponent mNetComponent;
#Override
public void onCreate() {
super.onCreate();
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
.build();
}
public NetComponent getmNetComponent() {
return mNetComponent;
}
}
Validator.java
#Module
public class Validator {
#Provides
com.mobsandgeeks.saripaar.Validator providesValidator(Application application) {
return new com.mobsandgeeks.saripaar.Validator(application);
}
}
I want to pass activity instance to the constructor of Validator in which I am using it.
Suppose I want to inject Validator in MainActivity.java then constructor should have MainActivity instance.
What approach should I take for this ? Should I initialize the dagger dependency in an activity for this and Do I need to create a new component for this ?
You can simply create constructor for your ValidatorModule:
#Module
public class Validator {
private final Activity activity;
public Validator(Activity activity) {
this.activity = activity;
}
#Provides
com.mobsandgeeks.saripaar.Validator providesValidator() {
return new com.mobsandgeeks.saripaar.Validator(activity);
}
}
Let me know if it is what you are looking for
I am using dagger2 for my application. I have one module which provides some dependencies like Retrofit, Gson etc.
NetModule.java
#Module
public class NetModule {
private String mBaseUrl;
public NetModule(String baseUrl) {
this.mBaseUrl = baseUrl;
}
#Provides
#Singleton
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}
#Provides
#Singleton
Cache provideOkHttpCache(Application application) {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(application.getCacheDir(), cacheSize);
return cache;
}
#Provides
#Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newBuilder()
//.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.cache(cache)
.build();
return okHttpClient;
}
#Provides
#Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(mBaseUrl)
.client(okHttpClient)
.build();
return retrofit;
}
}
NetComponent.java
#Singleton
#Component(modules = {AppModule.class, NetModule.class, Validator.class})
public interface NetComponent {
void inject(AuthenticationActivity authenticationActivity);
void inject(PaymentActivity paymentActivity);
}
AppApplication.java
#Override
public void onCreate() {
super.onCreate();
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
.netModule(new NetModule("https://corporateapiprojectwar.mybluemix.net/corporate_banking/mybank/"))
.build();
}
This approach was working until I had only one base url for my complete application. Now I have different base Url for AuthenticationActivity and PaymentActivity so I can not send Url in constructor of NetModule in onCreate of Application
Can anyone help me how to add dynamic base Url of retrofit using dagger2.
You can use #Named annotation Dagger2 user guide (see 'Qualifiers' section'):
In your NetModule.java:
#Provides
#Singleton
#Named("authRetrofit")
public Retrofit provideAuthRetrofit() {
// setup retrofit for authentication
return retrofit;
}
#Provides
#Singleton
#Named("paymentRetrofit")
public Retrofit providePaymentRetrofit() {
// setup retrofit for payments
return retrofit;
}
In your AuthenticationActivity:
#Inject
#Named("authRetrofit")
Retrofit retrofit;
And finally in your PaymentActivity.java:
#Inject
#Named("paymentRetrofit")
Retrofit retrofit;
Then dagger shall automatically inject Retrofit configured for payments into PaymentActivity and Retrofit configured for authentication into AuthenticationActivity