While there a few things you can do, it is your responsibility to make sure you don't pass null
to the LiveData
. In addition to that, every 'solution' is more a suppression of the warning, which can be dangerous (if you do get a null value, you might not handle it and Android Studio will not warn you).
Assert
You can add assert t != null;
. The assert will not be executed on Android, but Android Studio understands it.
class PrintObserver implements Observer<Integer> {
@Override
public void onChanged(@Nullable Integer integer) {
assert integer != null;
Log.d("Example", integer.toString());
}
}
Suppress the warning
Add an annotation to suppress the warning.
class PrintObserver implements Observer<Integer> {
@Override
@SuppressWarnings("ConstantConditions")
public void onChanged(@Nullable Integer integer) {
Log.d("Example", integer.toString());
}
}
Remove the annotation
This also works in my installation of Android Studio, but it might not work for you, but you could try to just remove the @Nullable
annotation from the implementation:
class PrintObserver implements Observer<Integer> {
@Override
public void onChanged(Integer integer) {
Log.d("Example", integer.toString());
}
}
Default methods
It's unlikely you can use this on Android, but purely from a Java perspective, you could define a new interface and add a null check in a default method:
interface NonNullObserver<V> extends Observer<V> {
@Override
default void onChanged(@Nullable V v) {
Objects.requireNonNull(v);
onNonNullChanged(v);
// Alternatively, you could add an if check here.
}
void onNonNullChanged(@NonNull V value);
}