Hilt (java) - Field Injection in Custom Class - java

So i'm trying to inject an object with the #Inject annotation in a class that is not related to:
Application (mediante #HiltAndroidApp)
Activity
Fragment
View
Service
BroadcastReceiver
But i can't do it. Maybe i'am doing something wrong because i can do the injection via constructor.
As you can see. The #Inject annotated object is null but the object received from the constructor is created.
Here is my code:
ApplicationModule
#Module
#InstallIn(ApplicationComponent.class)
public class ApplicationModule {
#Provides
public Context providesApplicationContext(#ApplicationContext Context context) {
return context;
}
#Provides
public CompositeDisposable providesCompositeDisposable() {
return new CompositeDisposable();
}
...
}
HomeViewModel
public class HomeViewModel extends ViewModel {
private static final String TAG = "HomeViewModel";
private CatalogInteractor catalogInteractor;
#Inject
public CompositeDisposable compositeDisposable;
#Inject
public HomeViewModel(CatalogInteractor catalogInteractor, CompositeDisposable compositeDisposable) {
this.catalogInteractor = catalogInteractor;
}
...
}
HomeFragment
#AndroidEntryPoint
public class HomeFragment extends BaseFragment {
private static final String TAG = "HomeFragment";
private DrawerLayout drawerLayout;
HomeViewModel viewModel;
LoginViewModel loginViewModel;
ViewModelProvider.Factory factory;
#Inject
HomeViewModelFactory homeViewModelFactory;
#Inject
CompositeDisposable compositeDisposable; // Injected here just to validate the correct creation
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
closeDrawer();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}
...
}
So i don't know if i'am doing something wrong or if it is a Hilt issue.
TLDR: I can inject fields with the #Inject annotation inside a fragment but i can't do it outside an android component class.

Related

Inject a ViewModel in a BottomSheetDialogFragment JAVA

I'm using dagger2 in my application and I'm trying to inject a ViewModel into BottomSheetDialogFragment but I don't know how.
I have the BaseApplication class like this:
public class BaseApplication extends DaggerApplication {
#Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
return DaggerAppComponent
.builder()
.application(this)
.build();
}
}
And the ViewModelFactory:
#Module
public abstract class ViewModelFactoryModule {
#Binds
public abstract ViewModelProvider.Factory mBindViewModelFactory(ViewModelProviderFactory mModelProviderFactory);
}
When I try to inject the viewmodel inside the BottomSheetDialogFragment it shows null exception
public class BottomSheetMoreOptions extends BottomSheetDialogFragment {
#Inject
FeedViewModel ViewModel;
}
The ViewModel constructor is:
#Inject
public FeedViewModel(#Named("notificationsRef") DatabaseReference mRef) {
Log.d(TAG, "HomeViewModel: is ready...");
this.mRef = mRef;
}
Actually to load the bottom sheet I'm passing the view model in its constructor:
BottomSheetMoreOptions bottomSheetMoreOptions = new BottomSheetMoreOptions(model.getFeed().getId(), viewModel);
bottomSheetMoreOptions.show(requireActivity().getSupportFragmentManager(),
"ModalBottomSheet");
Any help please in Java?

Dagger 2: inject an interface in a constructor

I'm trying to learn dagger 2 but I'm confused in injecting of constructor with interface. This is my below code :
MainActivity.java
public class MainActivity extends AppCompatActivity implements MainView {
// this keyword of request dependency . At compiling process, dagger will look at all of these annotations
//to create the exact dependency
#Inject MainPresenter mainPresenter ;
TextView textView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textview) ;
DaggerPresenterComponent.create().inject(this);
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
mainPresenter.doThings(8555) ;
}
});
}
/**********************************/
#Override
public void invokeRandomViewMethod(String msg) {
textView.setText(msg);
}
}
MainPresenter.java
public class MainPresenter {
private MainView mainView ;
#Inject
public MainPresenter(MainView mainView) {
this.mainView = mainView;
}
public void doThings(int value){
Random random = new Random();
int rand= random.nextInt(value) ;
if(mainView != null){
mainView.invokeRandomViewMethod("You random number is "+rand);
}
}
public interface MainView {
void invokeRandomViewMethod(String msg) ;
}
}
This is the Module :
#Module
public class PresenterModule {
#Provides
// this is the method that will provide the dependancy
MainPresenter provideMainPresenter(MainView mainView){
return new MainPresenter(mainView);
}
}
And this is the Component
#Component (modules = PresenterModule.class)
public interface PresenterComponent {
void inject(MainActivity activity) ;
}
When I run the code it shows me this error :
Error:(15, 10) error: com.imennmn.hellodagger2example.MainView cannot
be provided without an #Provides-annotated method.
com.imennmn.hellodagger2example.MainView is injected at
com.imennmn.hellodagger2example.presenterInjection.PresenterModule.provideMainPresenter(mainView)
com.imennmn.hellodagger2example.MainPresenter is injected at
com.imennmn.hellodagger2example.MainActivity.mainPresenter
com.imennmn.hellodagger2example.MainActivity is injected at
com.imennmn.hellodagger2example.simpleInjection.DataComponent.inject(activity)
My Question is how I can provide the interface MainView by inject it with dagger and bind the MainPresenter and MainActivity ?
Any help would be appreciated !
By following code:
MainPresenter provideMainPresenter(MainView mainView) {
return new MainPresenter(mainView);
}
You are telling dagger: "hey, whenever I ask you to inject MainPresenter, construct it using MainView".
But dagger complaints, because you haven't specified how exactly he should build/acquire MainView.
So, in your PresenterModule do this:
#Module
public class PresenterModule {
MainView mainView;
public PresenterModule(MainView mainView) {
this.mainView = mainView;
}
#Provides
MainPresenter provideMainPresenter() {
return new MainPresenter(mainView);
}
}
Then when building the component:
DaggerPresenterComponent.builder()
.presenterModule(new PresenterModule(this))
.build();
Your provideMainPresenter implicitly depends on a MainView. Dagger has no way to get it. You need to add a method to provide it:
#Module
public class PresenterModule {
#Provides
MainView provideMainView(){
// Provide MainView here somehow so Dagger can use this to create a MainPresenter
}
#Provides
// this is the method that will provide the dependancy
MainPresenter provideMainPresenter(MainView mainView){
return new MainPresenter(mainView);
}
}
Add abstract module with #Binds annotation, look at my impl of : AbstractTestSettingsFragmentModule.java
TestFragment.java
public class TestFragment extends Fragment{
#Inject TestFragmentContract.Presenter mPresenter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidSupportInjection.inject(this);
}
}
TestFragmentPresenterImpl.java
public class TestFragmentPresenterImpl implements TestFragmentContract.Presenter {
#Inject
public TestFragmentPresenterImpl(){
}
}
AbstractTestSettingsFragmentModule.java
#Module
public abstract class AbstractTestSettingsFragmentModule {
#Binds
#NonNull
public abstract TestSettingsFragmentContract.Presenter testSettingsFragmentPresenterImpl(TestSettingsFragmentImpl presenter);
}
ContributesModule.java
#Module
public abstract class ContributesModule {
#ContributesAndroidInjector(modules = {AbstractTestSettingsFragmentModule.class})
abstract TestSettingsFragment testSettingsFragment();
}
AppComponent.java
#Singleton
#Component(
modules = {
AndroidSupportInjectionModule.class,
ContributesModule.class,
AppModule.class,
})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
void inject(TheApplication theApplication);
#Override
void inject(DaggerApplication instance);
#Component.Builder
interface Builder {
#BindsInstance
Builder application(Application application);
AppComponent build();
}
}
You can use Assisted Injection with Dagger: https://dagger.dev/dev-guide/assisted-injection.html
Assisted injection is a dependency injection (DI) pattern that is used to construct an object where some parameters may be provided by the DI framework and others must be passed in at creation time (a.k.a “assisted”) by the user.

Inject activity using dagger

I try to create sample application with dagger 2 using mvp & RXAndroid, every thing work correctly but I cannot able to inject Activity the following is my AppComponent
#Singleton
#Component(modules = {AppModule.class})
public interface AppComponent {
void inject(App app);
void inject(MainActivity activity);
void inject(ResponseService service);
void inject(MainPresenter presenter);
}
and the following is my Module
#Module
public class AppModule {
private App app;
public AppModule(App app) {
this.app = app;
}
private static final String API_ENDPOINT = "url here";
#Provides
#Singleton
public ApiService apiService() {
OkHttpClient client = new OkHttpClient();
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ClassTypeAdapterFactory())
.registerTypeAdapter(Class.class, new ClassTypeAdapter()).create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
return retrofit.create(ApiService.class);
}
#Provides
#Singleton
ResponseService responseService() {
return new ResponseService(app.getComponent());
}
#Provides
#Singleton
MainPresenter mainPresenter() {
return new MainPresenter(app.getComponent());
}
#Provides
#Singleton
EventBus eventBus() {
return EventBus.getDefault();
}
}
I inject all things correctly and can work with them except ManiActivity when try to use it give me null pointer the following how i inject it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((App) getApplicationContext())
.getComponent()
.inject(this);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initRecyclerView();
presenter.setView(this);
}
but when try to use it as Context in My adapter and pass it to Picasso library give me the following exception java.lang.IllegalArgumentException: Context must not be null.
the following is how i use it
#Inject
MainActivity activity;
and use it in onBindViewHolder as following
Picasso.with(activity).load(response).fit().into(holder.ivCover);
My adapter code
public class ReAdapter extends RecyclerView.Adapter<ReAdapter.RViewHolder> {
private List<Response> responseList;
#Inject
MainActivity appContext;
public ReAdapter() {
}
public void setResponseList(List<Response> responseList) {
this.responseList = responseList;
notifyDataSetChanged();
}
#Override
public RViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.response_item, parent, false);
return new RViewHolder(view);
}
#Override
public void onBindViewHolder(RViewHolder holder, int position) {
final Response response = responseList.get(position);
Picasso.with(appContext).load(response.getValue().toLowerCase()).fit().into(holder.ivd);
}
#Override
public int getItemCount() {
return responseList != null ? responseList.size() : 0;
}
public class RViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ivd)
ImageView ivd;
public RViewHolder(View view) {
super(view);
ButterKnife.bind(this, itemView);
}
}
}
Can anyone help me to solve this issue ?
Your activity: MainActivity doesn't have an #Inject annotated constructor (and can't have, because it's created by the system).
In your AppModule there is no #Provides annotated method that returns MainActivity.
You are injecting the fields in your activity not in your adapter.
The result is Dagger has no idea how to create an object of type MainActivity.
The solution for this specific problem is to use the application context for Picasso or even better create a Picasso object with Dagger.
Update your AppModule with:
#Provides
#Singleton
Picasso providePicasso(App app) {
return Picasso.with(app);
}
In MainActivity add a field:
#Inject
ReAdapter adapter;
In ReAdapter modify the constructor and add a field for picasso:
private final Picasso picasso;
#Inject
public ReAdapter(Picasso picasso) {
this.picasso = picasso;
}
This way Dagger can create a singleton Picasso instance. The ReAdapter is annotated with #Inject (using constructor injection) so Dagger knows how to create it. By adding a ReAdapter field in MainActivity when you call component.inject(this) in MainActivity the adapter field will be initialized.

Injecting Context in MVP Presenter Android [duplicate]

This question already has an answer here:
How do I fix Dagger 2 error '... cannot be provided [...]'?
(1 answer)
Closed 5 years ago.
I am using MVP Architecture along with Dagger2. I want to get Context in my Presenter using constructor injection.
My Activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appintroduction);
activityComponent().inject(this);
ButterKnife.bind(this);
skipall.bringToFront();
}
My Presenter:
#ConfigPersistent
public class AppIntroPresenter extends BasePresenter<AppIntroMvpView> {
private final DataManager mDataManager;
private final Context ctx1;
#Inject
public AppIntroPresenter(DataManager dataManager,Context context) {
mDataManager = dataManager;
ctx1=context;
}
public void openCamView(Context ctx) {
ctx.startActivity(new Intent(ctx, CameraActivity.class));
}
}
My Application Component :
#Singleton
#Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
void inject(SyncService syncService);
#ApplicationContext Context context();
Application application();
RibotsService ribotsService();
PreferencesHelper preferencesHelper();
DatabaseHelper databaseHelper();
DataManager dataManager();
RxEventBus eventBus();
ClassService classService();
AnsweredQuestionService answeredQuestionService();
}
My Activity Component:
#PerActivity
#Subcomponent(modules = ActivityModule.class)
public interface ActivityComponent {
void inject(MainActivity mainActivity);
void inject(CameraActivity cameraActivity);
void inject(AppIntroActivity appIntroActivity);
}
My Application Module:
#Module
public class ApplicationModule {
protected final Application mApplication;
public ApplicationModule(Application application) {
mApplication = application;
}
#Provides
Application provideApplication() {
return mApplication;
}
#Provides
#ApplicationContext
Context provideContext() {
return mApplication;
}
#Provides
#Singleton
RibotsService provideRibotsService() {
return RibotsService.Creator.newRibotsService();
}
#Provides
#Singleton
ClassService provideClassService() {
return ClassService.Creator.newClassService();
}
#Provides
#Singleton
AnsweredQuestionService provideAnsweredQuestionService() {
return AnsweredQuestionService.Creator.newAnsweredQuestionService();
}
}
My Activity Module:
#Module
public class ActivityModule {
private Activity mActivity;
public ActivityModule(Activity activity) {
mActivity = activity;
}
#Provides
Activity provideActivity() {
return mActivity;
}
}
After running the code, i get error:
Error:(17, 8) error: [uk.co.ribot.androidboilerplate.injection.component.ActivityComponent.inject(uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity)] android.content.Context cannot be provided without an #Provides-annotated method.
android.content.Context is injected at
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroPresenter.<init>(…, context)
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroPresenter is injected at
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity.mAppIntroPresenter
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity is injected at
uk.co.ribot.androidboilerplate.injection.component.ActivityComponent.inject(appIntroActivity)
I know when i add context to constructor injection in My Presenter i get this error, but i am not able to figure out why? If i remove the context from constructor :
#Inject
public AppIntroPresenter(DataManager dataManager,Context context) {
mDataManager = dataManager;
ctx1=context;
}
Then everything works fine. But i need the context from injection. Please help me with this?
Since your constructor has members, you need to create a module and create there an instance annotated with #Provides and #Singleton, same as ApplicationModule.

Injecting field into module using dagger

I am trying to inject my android context from one module into another. This is my code so far:
UserProfileModule.java
#Module(
library = true
)
public class UserProfileModule {
#Inject Context _context;
#Provides
public AccountUtils.UserProfile provideUserProfile() {
return AccountUtils.getUserProfile(_context);
}
}
RootModule.java
#Module(
injects = {
PizzaApplication.class,
UserProfileModule.class,
MainActivity.class
},
includes = {
UserProfileModule.class
},
library = true
)
public class RootModule {
private final Context _context;
public RootModule(Context context) {
_context = context;
}
#Provides
#Singleton
public Context provideApplicationContext() {
return _context;
}
}
Anytime it tries to get the user profile it fails saying the object is null.]
EDIT:
PizzaApplication.java
public class PizzaApplication extends Application {
private ObjectGraph objectGraph;
#Override
public void onCreate() {
super.onCreate();
injectDependencies();
}
private void injectDependencies() {
objectGraph = ObjectGraph.create(new RootModule(this));
objectGraph.inject(this);
}
public void inject(Object object) {
objectGraph.inject(object);
}
}
MainActivity.java
public class MainActivity extends BaseActivity {
#InjectView(R.id.toolbar) public Toolbar _toolbar;
#InjectView(R.id.drawer) public DrawerFrameLayout _drawer;
#Inject public AccountUtils.UserProfile _profile;
#Inject public Context _context;
// private NavigationDrawerFragment navigationDrawerFragment;
#Override
protected void onCreate(Bundle saveInstanceState) {
tl;dr (Short version):
For a minimal working example of your code, see my code on GitHub
You don't need to / should't inject the Context from one module into another.
The order/direction of your module includes is reversed, the UserProfileModule should include the RootModule.
More details and comments on your code:
You don't need to inject something into a module, a module only provides dependencies. In your case simply making use of the module includes gives the functionality you want.
Remove the library = true from UserProfileModule, because you only need this when the module's providers aren't all used directly by the classes specified in the injects list.
As Niek Haarman said, you need to pass both RootModule and UserProfileModule instances to ObjectGraph.create in your PizzaApplication's onCreate.
You're doing inject(this) in PizzaApplication but it's got no dependencies, so the inject isn't necessary. Based on the sample code you've provided, this makes me think you're assuming that injecting on the Application-level will also inject Activity dependencies...? You need to do the inject on your Activity too.
You don't show if you're doing an inject in your Activity's onCreate -- that's most likely what's missing.
You're injecting Context into the Activity but that's not necessary since you can just use getApplicationContext() in the Activity.
Here's the working code:
RootModule:
#Module(
injects = {MainActivity.class},
library = true,
complete = false
)
public class RootModule {
private final Context _context;
public RootModule(Context context) {
_context = context;
}
#Provides
#Singleton
public Context provideApplicationContext() {
return _context;
}
}
UserProfileModule:
#Module(includes = {RootModule.class})
public class UserProfileModule {
#Provides
public AccountUtils.UserProfile provideUserProfile(Context context) {
return AccountUtils.getUserProfile(context);
}
}
MainActivity:
public class MainActivity extends BaseActivity {
#Inject
public AccountUtils.UserProfile _profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((PizzaApplication) getApplication()).inject(this);
_profile.message();
}
PizzaApplication:
public class PizzaApplication extends Application {
private ObjectGraph objectGraph;
#Override
public void onCreate() {
super.onCreate();
objectGraph = ObjectGraph.create(new RootModule(this), new UserProfileModule());
}
public void inject(Object object) {
objectGraph.inject(object);
}
}
You have
objectGraph = ObjectGraph.create(new RootModule(this));
But, includes = { UserProfileModule.class } is no magic. You have to create it yourself:
objectGraph = ObjectGraph.create(new RootModule(this), new UserProfileModule() );
Furthermore, the #Inject annotation on the Context doesn't work. You're better off modifying your provider method:
#Provides
public AccountUtils.UserProfile provideUserProfile(Context context) {
return AccountUtils.getUserProfile(context);
}
I cannot guarantee this will solve all your problems, but it will help you in the right direction.

Categories

Resources