Java – Despite setting SuppressWarnings, gradle prints warnings

Despite setting SuppressWarnings, gradle prints warnings… here is a solution to the problem.

Despite setting SuppressWarnings, gradle prints warnings

I have an Android app that imports into Android Studio. It contains some Java libraries. So far, so good.

Here’s how:

            @SuppressWarnings("deprecation")
        private Drawable getDrawable() {
            if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH)
                return activity.getResources().getDrawable(R.drawable.separator_gradient, activity.getTheme());
            else
                return activity.getResources().getDrawable(R.drawable.separator_gradient);
        }

Always print a devaluation warning:

:androidAnsatTerminal:compileDebugJava
C:\...\src\main\java\de\ansat\terminal\activity\widgets\druckAssistent\FahrkartenArtSelector.java:131: warning: [deprecation] getDrawable(int) in Resources has been deprecated
                return activity.getResources().getDrawable(R.drawable.separator_gradient);
                                               ^

1 warning

This is not the only @SuppressWarnings (“deprecation”) in my project. No warnings printed elsewhere…

For example:

    @SuppressWarnings("deprecation")
private void setBackgroundToNull(ImageView imgRight) {

    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        imgRight.setBackgroundDrawable(null);
    } else {
        imgRight.setBackground(null);
    }
}

AndroidManifest from self:

<uses-sdk
    android:minSdkVersion="15"
    android:targetSdkVersion="21" />

How can I get rid of this warning message?
I don’t want to turn off warnings or something on a global scale.

Edit:
If I just call getDrawable with the Theme parameter, this of course happens on SDK15 devices:

java.lang.NoSuchMethodError: android.content.res.Resources.getDrawable
        at de.ansat.terminal.activity.widgets.druckAssistent.FahrkartenArtSelector$3.getDrawable(FahrkartenArtSelector.java:128)

Solution

I found that this code triggers a warning for unknown reasons:

private Drawable getShadow(Context context) {
    @SuppressWarnings("deprecation")
    final Drawable drawable = context.getResources().getDrawable(R.drawable.shadow_top);
    return drawable;
}

Although this equivalent code does not:

private Drawable getShadow(Context context) {
    final int resId = R.drawable.shadow_top;
    @SuppressWarnings("deprecation")
    final Drawable drawable = context.getResources().getDrawable(resId);
    return drawable;
}

The extraction helper method also seems to work and solved the problem for me:

@SuppressWarnings("deprecation")
private Drawable getDrawable(Context context, int resId) {
    return context.getResources().getDrawable(resId);
}

Related Problems and Solutions