I setup the MVVM architecture with retrofit and dagger2 but when i run i found this exception
error: [ComponentProcessor:MiscError]
dagger.internal.codegen.ComponentProcessor was unable to process this
interface because not all of its dependencies could be resolved. Check
for compilation errors or a circular dependency with generated code.
AppModule.java
#Module(subcomponents = ViewModelSubComponent.class)
public class AppModule {
#Singleton
#Provides
ApiService provideService(OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.baseUrl(BaseRequest.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(new Gson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build()
.create(ApiService.class);
}
#Provides
CompositeDisposable provideCompositeDisposable() {
return new CompositeDisposable();
}
#Provides
#Singleton
public StethoInterceptor getSteltho() {
return new StethoInterceptor();
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient(Application application, StethoInterceptor stethoInterceptor, HttpLoggingInterceptor httpLoggingInterceptor) {
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
okHttpClient.connectTimeout(CommonUtils.TIMEOUT_IN_SEC, TimeUnit.SECONDS);
okHttpClient.readTimeout(CommonUtils.TIMEOUT_IN_SEC, TimeUnit.SECONDS);
okHttpClient.addInterceptor(getIntercepter(application));
if (BuildConfig.DEBUG) {
okHttpClient.addNetworkInterceptor(stethoInterceptor);
okHttpClient.interceptors().add(httpLoggingInterceptor);
}
return okHttpClient.build();
}
public Interceptor getIntercepter(final Application application) {
Interceptor headerAuthorizationInterceptor = new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
if (!CommonUtils.isNetworkConnected(application)) {
Request request = chain.request();
CacheControl cacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();
request = request.newBuilder().cacheControl(cacheControl).build();
String rawJson = chain.proceed(request).body().string();
Log.e("TAG", String.format("req response cache raw JSON response is: %s", rawJson));
return chain.proceed(request);
} else {
CacheControl cacheControl = new CacheControl.Builder().maxAge(1, TimeUnit.HOURS).build();
Request.Builder request = chain.request().newBuilder();
request.addHeader("Accept", "application/json");
//request.addHeader("Authorization", mAuth);
request.header("Cache-Control", "public, max-age=" + 90);
request.header(CACHE_CONTROL, cacheControl.toString());
Response response = chain.proceed(request.build());
return response;
}
}
};
return headerAuthorizationInterceptor;
}
#Provides
#Singleton
public HttpLoggingInterceptor httpLoggingInterceptor() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return httpLoggingInterceptor;
}
/*#Singleton
#Provides
ProjectRepository getrepository() {
return new ProjectRepository();
}*/
#Singleton
#Provides
ViewModelProvider.Factory provideViewModelFactory(ViewModelSubComponent.Builder viewModelSubComponent) {
return new ViewModelFactory(viewModelSubComponent.build());
}
MainActivityModule.java
#Module
public abstract class MainActivityModule {
#ContributesAndroidInjector(modules = FragmentBuildersModule.class)
public abstract MainActivity contributeMainActivity(); // #ContributesAndroidInjector(modules = FragmentBuildersModule.class)
}
FragmentBuildersModule.ktx
#Module
abstract class FragmentBuildersModule {
#ContributesAndroidInjector
internal abstract fun contributeHomeFragment(): HomeFragment
//#ContributesAndroidInjector
//abstract SeriesFragment contributeSeriesFragment();
}
ViewModelFactory.java
#Singleton
public class ViewModelFactory implements ViewModelProvider.Factory {
private final ArrayMap<Class, Callable<? extends ViewModel>> creators;
#Inject
public ViewModelFactory(ViewModelSubComponent viewModelSubComponent) {
creators = new ArrayMap<>();
// View models cannot be injected directly because they won't be bound to the owner's view model scope.
creators.put(ProjectViewModel.class, () -> viewModelSubComponent.homeViewModel());
// creators.put(ProjectListViewModel.class, () -> viewModelSubComponent.projectListViewModel());
}
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
Callable<? extends ViewModel> creator = creators.get(modelClass);
if (creator == null) {
for (Map.Entry<Class, Callable<? extends ViewModel>> entry : creators.entrySet()) {
if (modelClass.isAssignableFrom(entry.getKey())) {
creator = entry.getValue();
break;
}
}
}
if (creator == null) {
throw new IllegalArgumentException("Unknown model class " + modelClass);
}
try {
return (T) creator.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
AppComponent.java
#Singleton
#Component(modules = {AndroidInjectionModule.class, AppModule.class, MainActivityModule.class})//, MainActivityModule.class
public interface AppComponent {
#Component.Builder
interface Builder {
#BindsInstance
Builder application(Application application);
AppComponent build();
}
void inject(MyApplication appApplication);
}
AppInjector.java
public class AppInjector {
private static Application application;
private AppInjector() { }
public static void init(MyApplication appApplication) {
application = appApplication;
DaggerAppComponent.builder().application(appApplication).build().inject(appApplication);
appApplication.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
handleActivity(activity);
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
});
}
private static void handleActivity(Activity activity) {
if (activity instanceof HasSupportFragmentInjector) {
AndroidInjection.inject(activity);
}
if (activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() {
#Override
public void onFragmentCreated(FragmentManager fm, Fragment fragment, Bundle savedInstanceState) {
if (fragment instanceof Injectable) {
AndroidSupportInjection.inject(fragment);
}
}
}, true);
}
}
}
MyApplication.java
public class MyApplication extends Application implements HasActivityInjector {
private static PrefManager mPref;
private static MyApplication myApplication;
private Context context;
//private String dbUrl = "";
#Inject
DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;
public static MyApplication getInstance() {
return myApplication == null ? new MyApplication() : myApplication;
}
#Override
public void onCreate() {
super.onCreate();
this.context = this;
MultiDex.install(this);
AppInjector.init(this);
Fresco.initialize(this);
RemoteConfig.initConfig();
mPref = new PrefManager(this);
debugToolsInitilization();
}
#Override
public DispatchingAndroidInjector<Activity> activityInjector() {
return dispatchingAndroidInjector;
}
Throw exception when i add MainActivityModule module
Related
I am trying to implement new architecture (MVVM + RxJava2 + Dagger2 + Retrofit) in my existing project. I have set up whole above architecture and tested on HomeActivity. Dependencies injected in HomeViewModel. So Now I was trying to inject dependencies same as HomeViewModel in a FollowingViewModel of FollowingFragment which is a container Fragment of HomeActivity.But injected dependencies always return null(Not Initiziling).
I am following this project riggaroo/android-arch-components-date-countdown to Inject dependencies but in this sample, only activities are used no fragment. So I don't know what is happening and who to inject deps in multiple ViewModels.
Here is code for some important classes to understand:
AppApplication.class
public class AppApplication extends MultiDexApplication implements HasActivityInjector {
#Inject
DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;
#Override
public void onCreate() {
...........................
AppInjector.init(this)
..........................
}
#Override
public AndroidInjector<Activity> activityInjector() {
return dispatchingAndroidInjector;
}
}
AppInjector.class
public class AppInjector {
private AppInjector() {
}
public static void init(AppApplication appApplication) {
DaggerAppComponent.builder()
.application(appApplication)
.build()
.inject(appApplication);
appApplication
.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
handleActivity(activity);
}
});
}
private static void handleActivity(Activity activity) {
if (activity instanceof HasSupportFragmentInjector) {
AndroidInjection.inject(activity);
}
if (activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(
new FragmentManager.FragmentLifecycleCallbacks() {
#Override
public void onFragmentCreated(FragmentManager fm, Fragment f,
Bundle savedInstanceState) {
if (f instanceof Injectable) {
AndroidSupportInjection.inject(f);
}
}
}, true);
}
}
}
AppComponent.class
#Singleton
#Component(modules = {AndroidSupportInjectionModule.class,ActivityBuilderModule.class, AppModule.class, NetworkModule.class})
public interface AppComponent {
#Component.Builder
interface Builder {
#BindsInstance
Builder application(AppApplication application);
AppComponent build();
}
void inject(AppApplication app);
AppModule.class
#Module(includes = { ViewModelModule.class})
public class AppModule {
#Provides
Context provideContext(AppApplication application) {
return application.getApplicationContext();
}
}
ActivityBuilderModule.class
#Module
public abstract class ActivityBuilderModule {
#ContributesAndroidInjector(modules = FragmentBuildersModule.class)
abstract HomeActivity bindHomeActivity();
}
FragmentBuildersModule.class
#Module
public abstract class FragmentBuildersModule {
#ContributesAndroidInjector
abstract FollowingListFragment contributeFollowingListFragment();
}
ViewModule.class
#Module
public abstract class ViewModelModule {
#Binds
#IntoMap
#ViewModelKey(FollowingViewModel.class)
abstract ViewModel bindFollowingViewModel(FollowingViewModel followingViewModel);
#Binds
#IntoMap
#ViewModelKey(HomeViewModel.class)
abstract ViewModel bindHomeViewModel(HomeViewModel homeViewModel);
#Binds
abstract ViewModelProvider.Factory bindViewModelFactory(MyViewModelFactory factory);
}
NetworkModule.class
#Module
public class NetworkModule {
public NetworkModule(){}
#Provides
#Singleton
CompositeDisposable getCompositeDisposable() {
return new CompositeDisposable();
}
#Provides
#Singleton
Retrofit provideCall() {
// OKHttps and Retrofit code...
}
#Provides
#Singleton
#SuppressWarnings("unused")
public ApiCallInterface providesNetworkService(
Retrofit retrofit) {
return retrofit.create(ApiCallInterface.class);
}
#Provides
#Singleton
#SuppressWarnings("unused")
public Repository providesService(
ApiCallInterface networkService) {
return new Repository(networkService);
}
}
MyViewModelFactory.class
#Singleton
public class MyViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;
#Inject
public MyViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
this.creators = creators;
}
#SuppressWarnings("unchecked")
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
Provider<? extends ViewModel> creator = creators.get(modelClass);
if (creator == null) {
for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
if (modelClass.isAssignableFrom(entry.getKey())) {
creator = entry.getValue();
break;
}
}
}
if (creator == null) {
throw new IllegalArgumentException("unknown model class " + modelClass);
}
try {
return (T) creator.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
This class is used to create Instances of all viewModels. I have debugged and found only HomeViewModel instance is creating.
Now I have created HomeViewModel which is called from HomeActivity. Which is working fine. Now same implementaion is done in FollowingFragment but doesn't work. Let me show you how I have initialized FollowViewModel from FollowingListFragment.class
public class FollowingListFragment extends BaseFragment implementsInjectable {
#Inject
MyViewModelFactory myViewModelFactory;
private FollowingViewModel followingViewModel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
followingViewModel = ViewModelProviders.of(this, plownsViewModelFactory)
.get(FollowingViewModel.class);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_following_list, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
followingViewModel.getFollowings(id,curser);
}
}
Here is FollowingViewModel.class
public class FollowingViewModel extends ViewModel {
#Inject
Repository service;
#Inject
CompositeDisposable subscriptions;
#Inject
public FollowingViewModel() {
}
/*void setService(Repository service){
this.service = service;
}*/
void getFollowings(String id,String curser) {
if(service!=null) { **//HERE SERVICE RETURNS NULL**
Disposable subscription = service.getFollowings(id, curser, new IResponseCallback<FollowingResponse.FollowingResult>() {
#Override
public void onSuccess(FollowingResponse.FollowingResult followingResult) {
}
#Override
public void onError(Throwable throwable) {
}
});
subscriptions.add(subscription);
}else {
Log.d("FollowViewModel", "Service is null " );
}
}
Here is HomeActivity and HomeViewModel class code which is working fine.
HomeActivity.class
public class HomeActivity extends BaseActivity implements HasSupportFragmentInjector, Injectable {
#Inject
DispatchingAndroidInjector<Fragment> supportFragmentInjector;
#Inject
MyViewModelFactory viewFactory;
HomeViewModel homeViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
homeViewModel = ViewModelProviders.of(this,viewFactory).get(HomeViewModel.class);
homeViewModel.getFollowings("xyx",null);
}
#Override
public AndroidInjector<Fragment> supportFragmentInjector() {
return supportFragmentInjector;
}
}
HomeViewModel.class
public class HomeViewModel extends ViewModel {
#Inject
Repository service;
#Inject
CompositeDisposable subscriptions;
#Inject
public HomeViewModel() {
}
void getFollowings(String id,String curser) {
if(service!=null) { **// Returing null service**
}
}else {
Log.d("FollowViewModel", "Service is null " );
}
}
}
I have an application (module + component) where
#Singleton
#Component(modules = AppModule.class)
public interface AppComponent {
void inject(App app);
Serializer getSerializer();
ListOfCallingLists getListOfCallingLists();
Context getContext();
App getApp();
}
And
#Module
public class AppModule {
private final App app;
public AppModule(App app) {
this.app = app;
}
#Provides
Serializer provideSerializer() {
return new BinarySerializer();
}
#Provides
Context provideContext() {
return app;
}
#Provides
App provideApp() {
return app;
}
}
And
#Singleton
public class ListOfCallingLists implements Serializable {
...
#Inject
public ListOfCallingLists(Context context,
Serializer serializer) {
this.serializer = serializer;
...
}
}
And App is the application, I registered it in manifest:
public class App extends Application {
private AppComponent appComponent;
public static App get(Context context) {
return (App) context.getApplicationContext();
}
#Override
public void onCreate() {
super.onCreate();
if (appComponent == null)
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
appComponent.inject(this);
}
public AppComponent getComponent() {
return appComponent;
}
}
And finally the activity:
public class CallListsActivity extends AppCompatActivity {
#Inject
ListOfCallingLists list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
#Override
public void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// list here is null why?
}
}
In your AppComponent you need to add:
void inject(CallListsActivity callListActivity);
And in your CallListsActivity's onCreate() you need to tell how is your CallListsActivity injected.
For example, build your AppComponent and inject the activity, or you can use the new android injector: https://google.github.io/dagger/android.html
I have two module, AppModule and SplashViewModule
For AppModule:
#Module
public final class AppModule {
#NonNull
private final MyApplication mApp;
public AppModule(#NonNull MyApplication app) {
mApp = app;
}
#Provides
public Context provideAppContext() {
return mApp;
}
#Provides
public MyApplication provideApp() {
return mApp;
}
#Singleton
#Provides
public UserManager provideUserManager() {
return new UserManager();
}
}
For SplashviewModule
#Module
public final class SplashViewModule {
#Inject
UserManager mUserManager;
#Provides
public SplashInteractor provideInteractor() {
return new SplashInteractorImpl(mUserManager);
}
#Provides
public PresenterFactory<SplashPresenter> providePresenterFactory(#NonNull final SplashInteractor interactor) {
return new PresenterFactory<SplashPresenter>() {
#NonNull
#Override
public SplashPresenter create() {
return new SplashPresenterImpl(interactor);
}
};
}
}
And I inject these to my activity like this:
#Override
protected void setupComponent(#NonNull AppComponent parentComponent) {
DaggerSplashViewComponent.builder()
.appComponent(parentComponent)
.splashViewModule(new SplashViewModule())
.build()
.inject(this);
}
But this does not work. The UserManager would be null. How can I get the singleton instance of UserManager created by AppModule and inject it to SplashViewModule?
You don't have to declare UserManager mUserManager; in SplashViewModule. Just add a UserManager parameter for the method provideInteractor.
#Provides
public SplashInteractor provideInteractor(UserManager userManager) {
return new SplashInteractorImpl(userManager);
}
Can someone help me to resolve this issue, I'm trying to add dagger2 to my application getting this scope issue.
Error:(14, 1) error: com.bmx.presentation.authentication.login.LoginComponent depends on scoped components in a non-hierarchical scope ordering:
#com.bmx.di.scope.ActivityScope com.bmx.data.remote.AuthenticationRepositoryComponent
#com.bmx.di.scope.ActivityScope com.bmx.presentation.authentication.login.LoginComponent
#Module
public class AppModule {
private Application mApplication;
public AppModule(Application mApplication) {
this.mApplication = mApplication;
}
#Provides
#Singleton
Application provideApplication() {
return mApplication;
}
#Provides
#Singleton
public Resources provideResources(Context context) {
return context.getResources();
}
}
---------------------------------
#Module
public class NetModule {
String mBaseUrl;
public NetModule(String mBaseUrl) {
this.mBaseUrl = mBaseUrl;
}
#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) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.cache(cache);
return client.build();
}
#Provides
#Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(mBaseUrl)
.client(okHttpClient)
.build();
}
#Provides
#Singleton
public BmxRestService provideBmxRestService(Retrofit retrofit) {
return retrofit.create(BmxRestService.class);
}
}
---------------------------------------------
#Singleton
#Component(modules = {NetModule.class,AppModule.class})
public interface ApiComponent {
BmxRestService getBmxRestService();
Application getApplication();
}
-----------------------------------------------------
public interface AuthenticationRepository {
Observable<List<UserProfile>> doLogin(String userName, String password);
Observable<List<UserProfile>> doSignUp(String firstName, String lastName,String email,String password);
}
--------------------------------------------------------------
public class AuthenticationRepositoryImpl implements AuthenticationRepository {
private BmxRestService BmxRestService;
#Inject
public AuthenticationRepositoryImpl(#NonNull final BmxRestService BmxRestService) {
this.BmxRestService = BmxRestService;
}
//implementation
}
-------------------------------------------
#ActivityScope
#Module
public class AuthenticationRepositoryModule {
#Provides
#ActivityScope
public AuthenticationRepository provideAuthenticationRepository(BmxRestService BmxRestService) {
return new AuthenticationRepositoryImpl(BmxRestService);
}
}
-----------------------------
#ActivityScope
#Component(modules = {AuthenticationRepositoryModule.class},dependencies = ApiComponent.class)
public interface AuthenticationRepositoryComponent {
AuthenticationRepository getAuthenticationRepository();
}
-----------------------------------
#Module
public class LoginPresenterModule {
private final LoginContract.View mView;
public LoginPresenterModule(LoginContract.View mView) {
this.mView = mView;
}
#Provides
#ActivityScope
LoginContract.View provideLoginContractView(){
return this.mView;
}
}
----------------------------------------------
#ActivityScope
#Component(dependencies = AuthenticationRepositoryComponent.class, modules = LoginPresenterModule.class)
public interface LoginComponent {
void inject(LoginActivity activity);
}
----------------------------------------
public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter{
private Scheduler mainScheduler, ioScheduler;
private AuthenticationRepository mAuthenticationRepository;
#Inject
public LoginPresenter(#NonNull final AuthenticationRepository authenticationRepository,#NonNull final LoginContract.View loginView) {
super(loginView);
this.mView =loginView;
this.mAuthenticationRepository =authenticationRepository;
this.mainScheduler = AndroidSchedulers.mainThread();
this.ioScheduler = Schedulers.io();
}
//implementation
}
----------------------
public class LoginActivity extends AppCompatActivity implements LoginContract.View {
private static final String TAG = "LoginActivity";
#Inject
LoginPresenter mLoginPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
}
-----------------------
public class BmxApp extends Application {
private ApiComponent apiComponent;
#Override
public void onCreate() {
super.onCreate();
initializeNetComponent();
}
private void initializeNetComponent() {
apiComponent = DaggerApiComponent.builder().netModule(new NetModule(BuildConfig.BASEURL)).appModule(new AppModule(this)).build();
}
public ApiComponent getApiComponent() {
return apiComponent;
}
}
---------------
#Documented
#Scope
#Retention(RetentionPolicy.RUNTIME)
public #interface ActivityScope {
}
I am trying to use Dagger 2 for instantiating a Retrofit interface. The CloudContactDataStore class injects the RestClient and calls its methods.
When I instantiate a CloudContactDataStore object, its RestClient attribute has null value.
public class CloudContactDataStore implements ContactDataStore {
#Inject RestClient restClient;
public CloudContactDataStore() {
this.initializeInjector();
}
private void initializeInjector() {
DaggerApiComponent.builder()
.apiModule(new ApiModule())
.build()
.inject(this);
}
#Override
public Observable<ContactEntity> contactLogin(String contactId) {
return this.restClient.contactLogin(contactId); // Here restClient is null!
}
}
Here is how I create the Dagger Module and Component:
#Singleton
#Component(modules = ApiModule.class)
public interface ApiComponent {
void inject(ContactDataStore contactDataStore);
}
#Module
public class ApiModule {
#Provides public RestClient provideRestClient(ApiService apiService) {
return new RestClientImpl(apiService);
}
#Provides public ApiService provideApiService(RestAdapter restAdapter) {
return restAdapter.create(ApiService.class);
}
#Provides public RestAdapter provideRestAdapter() {
return RestApiAdapter.getInstance();
}
}
Now, the RestClient class and its implementation:
public interface RestClient {
Observable<ContactEntity> contactLogin(String contactId);
}
public class RestClientImpl implements RestClient {
ApiService apiService;
#Inject
public RestClientImpl(ApiService apiService) {
this.apiService = apiService;
}
#Override
public Observable<ContactEntity> contactLogin(String contactId) {
return apiService.login(contactId, "xxx-xxx-xxx");
}
}
The ApiService interface is the Retrofit interface:
public interface ApiService {
String API_BASE_URL = "http://192.168.1.2";
#POST("/login")
Observable<ContactEntity> login(#Body String id, #Header("Key") String key);
}
And finally, the RestApiAdapter:
public class RestApiAdapter {
private static RestAdapter sharedInstance = null;
public static RestAdapter getInstance() {
if (sharedInstance == null){
sharedInstance = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(ApiService.API_BASE_URL)
.build();
}
return sharedInstance;
}
}
Can anyone see what I am doing wrong?
Thanks!
This has the same problem as in Why Dagger inject is not working but component.getObject yes and the same solution. That is you need to either change your inject(ContactDataStore) method to inject(CloudContactDataStore) so it can see the field that needs injecting, or you need to add a method in ContactDataStore that allows you to inject the method yourself.