Dagger hilt injected object is null in custom view

Viewed 51

I am trying to inject a class (ExampleClass) in a custom view (CustomView), it extends from a class called BaseWidget which extends from LinearLayout.

I have this class, which I want to inject to my custom view.

class ExampleClass @Inject constructor(val api: Api) {...}

The Api is provided in a @Module (because it's Retrofit).

CustomView is declared in the XML layout of a Fragment (ExampleFragment), which is contained in an Activity ExampleActivity

Here comes the code:

Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<com.example.ui.widget.CustomView
    android:id="@+id/customview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

CustomView (in java):

@AndroidEntryPoint
public class CustomView extends BaseWidget {

@Inject
ExampleClass exampleClassInjected;

...
}

Fragment and activity are also annotated with @AndroidEntryPoint.

The thing is that the value of exampleClassInjected is always null in CustomView, but if I move that to the fragment or the activity, it has a value.

I don't understand why is null in the custom view but not in fragment or activity, what I'm missing?

EDIT:

I was trying to use the injected class in the CustomView constructor, and it's null in that moment, but if I wait until Fragment's onViewCreated() that injected class in customView is not null anymore, so I don't really understand, dagger is working properly, but it seems it's waiting until fragment is full created to inject the custom view

1 Answers

no need for any annotation for custom classes ,if you use constructer inject . >> just remove @AndroidEntryPoint .......... if you want field injection read my answer for this question.how filed injection work with dagger-hilt

Related