Java – Method reference requires API level 22

Method reference requires API level 22… here is a solution to the problem.

Method reference requires API level 22

Based on Use Java 8 language features method reference compatibility Any minSdkVersion, then why do method references require API level 22?

Currently I’m using Android Studio 3.2.1 with com.android.tools.build:gradle:3.2.1 and JDK 1.8 in build-gradle I have:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Example

public class SimpleBundleEntry<V> extends BundleEntry<V> {

public SimpleBundleEntry(String key, V value, 
                            BundleWriter<V> writer, BundleReader<V> reader) 
    {/*init*/}

// ...

public interface BundleReader<V> {
        V readValue(Bundle bundle, String key);
    }

public interface BundleWriter<V> {
        void writeValue(Bundle bundle, String key, V value);
    }
}

Problematic code

public static BundleEntry<Boolean> ofBoolean(String key, Boolean value) {
    return new SimpleBundleEntry<>(key, value,
            Bundle::putBoolean, // <------------------- PROBLEM HERE
            (bundle, k) -> bundle.getBoolean(k));
}

Solution

I don’t know what method you’re calling, but there are two different things here.

Android is built on java, which means you have a version of Java installed on your phone to run the operating system.

With the update of Java, some methods were added to the framework, so some methods existed in 1.8 but not in 1.7

But Android is also a platform for getting updates, and we’re in version 28 ( https://developer.android.com/studio/releases/platforms)。

Each version of

this version has a new set of methods that did not exist in previous versions.

So, if you are

calling a method introduced in Android 22 and you are running your application on an API 16 phone, this will cause a crash.

To prevent this, you must surround the code that requires Android API 22

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES. LOLLIPOP_MR1) {
    call the method that needs API 22 at least
} else {
    do something backward compatible
}

Related Problems and Solutions