I'm using ContextCompat.getColor to get color resources and have backwards compatibility for deprecated methods like Context's getColor.
E.g.:
ContextCompat.getColor(context, R.color.black)
This works well everywhere I've used it so far, but I'm seeing a lot of problems in my app's crash logs like the following:
Caused by java.lang.NoSuchMethodError: No virtual method getColor(I)I in class Landroid/content/Context; or its super classes (declaration of 'android.content.Context' appears in /system/framework/framework.jar)
at android.support.v4.content.ContextCompat.getColor(ContextCompat.java:418)
at com.myapp.MyView.method(MyView.kt:XXX)
Looking at the phones/Android versions, they are all in the Marshmallow family (6.0 – 6.1), and I added some logging around API detection, and can confirm that they are at API level 23.
In terms of manufacturers, they are Xiaomi, Lenovo, ZTE, and OPPO.
My solution so far is:
int color;
try {
color = ContextCompat.getColor(context, colorRes);
} catch (NoSuchMethodError e) {
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.M) {
// log for a while, to catch if any other versions/devices have issues
Timber.e(
e,
"Couldn't use getColor in API level %s (%s)",
Build.VERSION.SDK_INT,
Build.VERSION.RELEASE
);
}
color = context.getResources().getColor(colorRes);
}
// Now I know color has a value :D
This works fine but it's far from ideal, as I was hoping to be able to use ContextCompat transparently and forget about this.
I've tried appcompat versions 27.1.0 and 28.0.0. Has anyone come across this problem? Is there a better way to deal with it?