I'm new to dagger and hilt, I'm trying to use Hilt to get my adapter injected to my fragment using a builder (the fragment is actually in a fragment pager adapter so there's multiple instance of it and the adapter), it seems set up correctly, I build the component before super in onCreate but the adapter is null when trying to access it later in the fragment, I wonder if maybe I need to provide it somehow later on so for instance I have my adapter in my fragment
@AndroidEntryPoint
public class CardHolderFragment extends Fragment {
public CardAdapter cardAdapter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
DaggerCardAdapterComponent.builder()
.cardAdapterDependencies(() -> layoutIdentifier)
.build().inject(this);
super.onCreate(savedInstanceState);
cardAdapter.notifyDataSetChanged(); // CardAdapter.notifyDataSetChanged()' on a null object reference
so my question is if the component is setup correctly should this work or am I missing a step? What I feel like doing is something like cardAdapter = DaggerCardAdapterComponent.getCardAdapter but I can't put a provides methods in a component, I had a look through the dagger migration guide here which is a little complicated for me as I only had a few weeks with dagger before switching to hilt, but the guide mentions
Finally, you may have to redesign some things if they were configured differently for different activity or fragment components. For example, you could use a new interface on the activity to provide the object.
so I tried this which makes me implement the interface and then return a card adapter but I wasn't sure what I should be returning here, any help welcome
heres my card adapter component
@Component(dependencies = CardAdapterDependencies.class, modules = {TypeFactoryModule.class,
ItemTouchListenerModule.class, GlideModule.class})
public interface CardAdapterComponent {
void inject(CardHolderFragment cardHolderFragment);
@Component.Builder
interface Builder {
Builder cardAdapterDependencies(CardAdapterDependencies cardAdapterDependencies);
CardAdapterComponent build();
}
interface HasCardAdapter{
CardAdapter getCardAdapter();
}
}
and heres my card adapter constructor
@Inject
public CardAdapter(
ItemTouchListener onItemTouchListener,
String layoutIdentifier,
TypeFactory typeFactory,
RequestManager glide
) {
this.onItemTouchListener = onItemTouchListener;
this.typeFactory = typeFactory;
this.layoutIdentifier = layoutIdentifier;
this.glide = glide;
this.elements = new ArrayList<>();
}