I have problem with returning nullable NfcAdapter through my Dagger module. Here it is:
@Provides
@Singleton
@Nullable
public NfcAdapter provideNfcAdapter() {
return NfcAdapter.getDefaultAdapter(context);
}
However the project can't be build and i receive error message:
error: [dagger.android.AndroidInjector.inject(T)] android.nfc.NfcAdapter is not nullable, but is being provided by @Provides @Singleton @javax.annotation.Nullable android.nfc.NfcAdapter
How it can be resolved? I have similiar provide method for my BluetoothAdapter and it works as expected.
I try to initialize it as below in my Activity:
var nfcAdapter: NfcAdapter? = null @Inject set
You'll need to add a @Nullable annotation to the field. Any annotation that has the simple name "Nullable" will do, as listed in the docs and the code.
Though you can mark the nullability in Kotlin using ?, this does not publish the "nullable" information from Kotlin to Java: a Java processor like Dagger cannot read the class file to determine that the field is meant to be nullable. (This is possible through some Kotlin reflection, but Dagger does not do it as of v2.17.) Though your code is safe, Dagger cannot determine that by reading the bytecode, and it throws an error.
Brief Answer
--> Delete @Nullable line
It happens because you put the @Nullable annotation in a method that can not return null. Android Studio is telling you that NfcAdapter can not be null. Deleting the @Nullable annotation should work.
Deep explanation
In my case, I had this method in my dagger 2 module.
@Provides
@Singleton
@Nullable
AuthenticationInterceptor provideInterceptor(@Nullable String authToken) {
if (authToken != null) {
return new AuthenticationInterceptor(authToken);
} else {
return null;
}
}
I found out that my class AuthenticationInterceptor which implements Interceptor
public class AuthenticationInterceptor implements Interceptor {
}
couldn't return null (and I was returning null from it in case there was no authToken), then AS gave me the following error.
AuthenticationInterceptor is not nullable, but is being provided by @Provides @Singleton ...
Not returning null from my method resolved the issue. (Removing the @Nullable annotation and excluding the return null).
@Provides
@Singleton
AuthenticationInterceptor provideInterceptor(@Nullable String authToken) {
return new AuthenticationInterceptor(authToken);
}
Conclusion
I did that because I was already handling these nullable things in the activities. In case the user has no authorization token, I didn't even try to make the retrofit call. I just asked him to sign in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With