I need to inject the creation of NetReceiver
object into my Fragment but I get the following error:
error: [Dagger/MissingBinding] com.example.myapp.NetReceiver.OnNetCallback cannot be provided without an @Provides-annotated method.
Let me show you what I have tried. This is my NetReceiver
class:
public class NetReceiver extends BroadcastReceiver {
private OnNetCallback onNetCallback;
@Inject
public NetReceiver(OnNetCallback onNetCallback) {
this.onNetCallback = onNetCallback;
}
@Override
public void onReceive(Context context, Intent intent) {
if (someCondition) {
onNetCallback.enableOperation(true);
}
}
public interface OnNetCallback {
void enableOperation(boolean isOk);
}
}
As you can see, I want to inject in the constructor a NetCallback
object. I have also created a Module class that looks like this:
@Module
public abstract class NetReceiverModule {
@ContributesAndroidInjector //Error?!?!?!?!
abstract NetReceiver.OnNetCallback provideOnNetCallback();
@Singleton
@Provides
static NetReceiver provideNetReceiver(NetReceiver.OnNetCallback onNetCallback) {
return new NetReceiver(onNetCallback);
}
}
This is how my fragment look liked when it worked:
public class MapFragment extends Fragment implements NetReceiver.OnNetCallback {
private NetReceiver netReceiver;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate View
netReceiver = new NetReceiver(this); //Worked
}
@Override
public void onResume() {
super.onResume();
mainActivity.registerReceiver(netReceiver, intentFilter);
}
@Override
public void onPause() {
super.onPause();
mainActivity.unregisterReceiver(netReceiver);
}
}
And this is how it looks when it is not working:
public class MapFragment extends DaggerFragment implements NetReceiver.OnNetCallback {
@Inject NetReceiver netReceiver;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate View
//netReceiver = new NetReceiver(this); //Worked
}
@Override
public void onResume() {
super.onResume();
mainActivity.registerReceiver(netReceiver, intentFilter);
}
@Override
public void onPause() {
super.onPause();
mainActivity.unregisterReceiver(netReceiver);
}
}