Inject presenter into activity via Dagger - java

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.

Related

NPE while injecting Retrofit with Dagger

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);
}

How do I inject dependencies into an Activity that require an argument from a previous Activity?

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);
}
}

How to send activity instance to module in a constructor in dagger2

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

Dagger can not provide my dependencies

I'm having a problem with Dagger 2.
I want a general NetworkModule where I can share my retrofit, etc.. and then later on I want subcomponents so that per flow I have different Retrofit Interfaces for example login, ...
My setup right now is:
#Module
public class NetworkModule {
#Provides
#Singleton
#Named("Default")
Retrofit provideRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("myUrl")
.build();
return retrofit;
}
}
I also have a ApplicationModule ( I don't know if this is the correct way to have a ApplicationModule ).
#Module
public class ApplicationModule {
private Application application;
public ApplicationModule(Application application) {
this.application = application;
}
#Provides
#Singleton
Application providesApplication() {
return this.application;
}
}
And last but not least my Component that binds the two together:
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetworkComponent {
Retrofit provideRetrofit();
void inject(MainActivity activity);
}
Now I don't see the problem but when I do:
((MyApplication) getApplication()).getNetworkComponent().inject(this);
Where this is created as:
DaggerNetworkComponent.builder().applicationModule(new ApplicationModule(this)).build();
I can't compile and I get the error:
retrofit2.Retrofit cannot be provided without an #Inject constructor or from an #Provides- or #Produces-annotated method.
Add #Named("Default") to your Retrofit provideRetrofit(); in NetworkComponent
You can refer to the following classes for the usage of dagger 2 and retrofit :
Injector.java
public class Injector {
// Singleton instance
private static Injector instance;
// components
private AppComponent appComponent;
// Private constructor to make it singleton
private Injector() {
}
/**
* Get the singleton Injector instance
*
* #return Injector
*/
private static Injector instance() {
if (instance == null) {
instance = new Injector();
}
return instance;
}
/**
* Creates application component which used of injection later.
*
* #param application
*/
public static void createApplicationComponent(Application application) {
if (instance().appComponent == null) {
instance().appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(application))
.build();
}
}
/**
* Returns the component for injection.
*
* #return
*/
public static AppComponent component() {
return instance().appComponent;
}
}
AppComponent.java
#Singleton
#Component(modules = {
AppModule.class,
ApiModule.class,
})
public interface AppComponent {
// Other utility classes for injection
}
ApiModule.java which similar to your network module class
#Module
public class ApiModule {
#Provides
#Singleton
public Retrofit provideApi(
OkHttpClient client,
Converter.Factory converterFactory,
CallAdapter.Factory callAdapterFactory) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Config.API_BASE_URL)
.client(client)
.addConverterFactory(converterFactory)
.addCallAdapterFactory(callAdapterFactory)
.build();
return retrofit;
}
}
AppModule.java
#Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
#Provides
#Singleton
public Application provideApplication() {
return application;
}
#Provides
#Singleton
public Context provideContext() {
return application;
}
}
later in your activity class you can use Injector.component().inject(this); to inject dagger 2 dependencies
For more clarification you can refer this github repo

Dagger 2 component dependency not working

The dagger modules
#Module
public class NetModule {
#Provides
#Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
return gsonBuilder.create();
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient() {
OkHttpClient client = new OkHttpClient();
return client;
}
#Provides
#Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(BuildConfig.SERVER_BASE_URL)
.client(okHttpClient)
.build();
return retrofit;
}
}
#Module
public class AppModule{
private Application application;
public AppModule(Application application){
this.application = application;
}
#Provides
#Singleton
Application provideApplication() {
return application;
}
}
#Module
public class ImageModule {
#Provides
#Singleton
Picasso providePicasso(Application application, OkHttpClient client) {
Picasso.Builder builder = new Picasso.Builder(application);
builder.downloader(new OkHttp3Downloader(client));
return builder.build();
}
}
These are the components
#Singleton
#Component(modules={NetModule.class})
public interface NetComponent {
void inject(MyFragment fragment);
}
#Singleton
#Component(modules={AppModule.class, ImageModule.class}, dependencies = {NetModule.class})
public interface ImageComponent {
void inject(MyFragment fragment);
}
This is how I am registering the components
public class MyApp extends Application{
#Override
public void onCreate() {
netComponent = DaggerNetComponent.builder()
.netModule(new NetModule())
.build();
imageComponent = DaggerImageComponent.builder()
.appModule(new appModule(this))
.imageModule(new ImageModule())
.build();
}
}
And in the fragment
public class MyFragment extends Fragment {
#Inject
Retrofit retrofit;
#Inject
Picasso picasso;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MyApp)getActivity().getApplication()).getNetComponent().inject(this);
((MyApp)getActivity().getApplication()).getImageComponent().inject(this);
....
}
}
I am getting compilation error as below
Error:(25, 10) error: com.squareup.picasso.Picasso cannot be provided
without an #Inject constructor or from an #Provides- or
#Produces-annotated method.
What is the best way to achieve this in dagger 2?
When Component A depends on type B, you're saying that every zero-arg getter on B will be available in A's graph. This means that you don't need to call inject separately on NetComponent, but you do need to expose OkHttpClient in NetComponent's definition.
This means NetComponent would look like this:
#Singleton
#Component(modules={NetModule.class})
public interface NetComponent {
/** Exposes OkHttpClient. Used by components depending on NetComponent. */
OkHttpClient getOkHttpClient();
}
And your onCreateView could look like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MyApp)getActivity().getApplication()).getImageComponent().inject(this);
}
Internally, Dagger generates the DaggerNetComponent and DaggerImageComponent in two separate steps, but has ImageComponent call the new getOkHttpClient method. This also means that DaggerImageComponent can accept any implementation of NetComponent, not just the one Dagger generates.
Related resources:
What is the purpose of the non-inject methods in Components in Dagger 2? (see David Rawson's answer)
Dagger 2 subcomponents vs component dependencies
Dagger docs on component dependencies and its link to provision methods

Categories

Resources