PrimitiveIterator not working with API De-sugaring in Android

I am trying to use PrimitiveIterator.OfInt, PrimitiveIterator.OfLong etc in my code. My min SDK version is 16 and hence to get support of Java 8 classes and Interfaces, I followed API desugaring steps as given here :

https://developer.android.com/studio/write/java8-support#library-desugaring

Hence in my module build.gradle i made the following changes :

defaultConfig{
    multiDexEnabled true
}

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
        coreLibraryDesugaringEnabled true
    }

dependecies{
        implementation "androidx.multidex:multidex:$multidex_version"
        coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

After this I was able to use classes like "java.util.Instant", "java.util.Stream" but still could not use PrimitiveIterator interface. It is still asking to add annotation for API version 24.

Also here it shows support for the required Interface but does not seem to have so . https://developer.android.com/studio/write/java8-support-table

Answers 1

  • This is most probably a Lint issue.

    I ran the instrumented test below on a virtual device using an API 16 image and on a Wiko Lenny 2 which runs on Android 5.1 (API 22). In both cases the test succeeded when coreLibraryDesugaringEnabled was set to true and gave a ClassNotFoundException when coreLibraryDesugaringEnabled was set to false.

    So I would say, mark the statements where Lint has an issue with @SuppressLint("NewApi") and you are done.

    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    
    import java.util.PrimitiveIterator;
    
    import androidx.test.ext.junit.runners.AndroidJUnit4;
    
    @RunWith(AndroidJUnit4.class)
    public class PrimitiveIteratorTest {
    
        PrimitiveIterator.OfInt intIterator;
    
        @Before
        public void setUpIterator() {
            intIterator = new PrimitiveIterator.OfInt() {
    
                final int[] intArray = {1,2,3,4,5,6,7,8,9,10};
                int index = -1;
    
                @Override
                public int nextInt() {
                    return intArray[++index];
                }
    
                @Override
                public boolean hasNext() {
                    return index < intArray.length - 1;
                }
            };
        }
    
        @Test
        public void primitiveIteratorTest(){
    
            int first = intIterator.nextInt();
            int second = intIterator.nextInt();
    
            assert(first == 1);
            assert(second == 2);
            assert(intIterator.hasNext());
        }
    }
    

Related Articles