react-native-contacts: Build Error - package android.support.annotation does not exist

I am upgrading from RN 0.55.3 to 0.59.8 (manually).

I’ve got it running well on iOS, but when I run react-native run-android I’m getting the following error:

Task :react-native-contacts:compileDebugJavaWithJavac FAILED /node_modules/react-native-contacts/android/src/main/java/com/rt2zz/reactnativecontacts/ReactNativeContacts.java:3: error: package android.support.annotation does not exist import android.support.annotation.NonNull;

I already tried react-native unlink react-native-contacts && react-native link react-native-contacts

I have also tried rm -rf node_modules && yarn as well as watchman watch-del-all && react-native run-android --reset-cache

Android Files

Click To Expand

android/build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        // jitpack repo is necessary to fetch ucrop dependency
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.google.com' }
        google()
        jcenter()
    }
    configurations.all {
      resolutionStrategy.force "com.android.support:support-v4:26.1.0"
    }
}

android/app/build.gradle:

apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    signingConfigs {
        debug {
            keyAlias 'androiddebugkey'
            keyPassword 'android'
            storeFile file('./keystore/debug.keystore')
            storePassword 'android'
        }
        release {
            if (project.hasProperty('MyApp_RELEASE_STORE_FILE')) {
                storeFile file(MyApp_RELEASE_STORE_FILE)
                storePassword MyApp_RELEASE_STORE_PASSWORD
                keyAlias MyApp_RELEASE_KEY_ALIAS
                keyPassword MyApp_RELEASE_KEY_PASSWORD
            }
        }
    }
    compileSdkVersion rootProject.ext.compileSdkVersion

     compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    defaultConfig {
        applicationId "mx.com.MyApp"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        missingDimensionStrategy 'react-native-camera', 'general'
        versionCode 127
        versionName "2.1.27"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        vectorDrawables.useSupportLibrary = true
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation project(':react-native-contacts')
    implementation project(':@react-native-community/async-storage')
    implementation project(':react-native-svg')
    implementation project(':react-native-mixpanel')
    implementation project(':react-native-fbsdk')
    implementation project(':react-native-webview-android-file-upload')
    implementation(project(':react-native-firebase')) {
        transitive = false
    }
    implementation project(':react-native-share')
    implementation project(':react-native-localization')
    implementation project(':react-native-image-crop-picker')
    implementation project(':react-native-carrier-info')
    implementation project(':react-native-sound')
    implementation project(':react-native-version-number')
    implementation project(':react-native-device-info')
    implementation project(':react-native-default-preference')
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.facebook.react:react-native:+'
    implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
    implementation project(':react-native-fs')
    implementation 'com.google.android.gms:play-services-base:16.0.0'
    implementation 'com.google.android.gms:play-services-maps:16.0.0'
    implementation "com.google.firebase:firebase-core:16.0.0"
    implementation 'com.google.firebase:firebase-messaging:17.0.0'
    implementation "com.google.firebase:firebase-storage:15.0.2"
    implementation project(':react-native-maps')
    implementation 'me.leolin:ShortcutBadger:1.1.21@aar'
    implementation project (':react-native-camera')
    implementation "com.android.support:support-v4:26.1.0"
    implementation 'com.android.support:support-annotations:28.0.0'
    implementation 'com.facebook.fresco:fresco:1.9.0'
    implementation 'com.facebook.fresco:animated-gif:1.9.0'
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply plugin: 'com.google.gms.google-services'

android/settings.gradle:

rootProject.name = 'MyApp'
include ':react-native-contacts'
project(':react-native-contacts').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-contacts/android')
include ':@react-native-community/async-storage'
project(':@react-native-community/async-storage').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/async-storage/android')
include ':react-native-svg'
project(':react-native-svg').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-svg/android')
include ':react-native-mixpanel'
project(':react-native-mixpanel').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-mixpanel/android')
include ':react-native-fbsdk'
project(':react-native-fbsdk').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk/android')
include ':react-native-webview-android-file-upload'
project(':react-native-webview-android-file-upload').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview-android-file-upload/android')
include ':react-native-default-preference'
project(':react-native-default-preference').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-default-preference/android')
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
include ':react-native-version-number'
project(':react-native-version-number').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-version-number/android')
include ':react-native-share'
project(':react-native-share').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-share/android')
include ':react-native-localization'
project(':react-native-localization').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-localization/android')
include ':react-native-carrier-info'
project(':react-native-carrier-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-carrier-info/android')
include ':react-native-image-crop-picker'
project(':react-native-image-crop-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-crop-picker/android')
include ':react-native-sound'
project(':react-native-sound').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sound/android')
include ':react-native-firebase'
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')
include ':react-native-camera'
project(':react-native-camera').projectDir = new File(rootProject.projectDir, 	'../node_modules/react-native-camera/android')
include ':react-native-fs'
project(':react-native-fs').projectDir = new File(settingsDir, '../node_modules/react-native-fs/android')
include ':react-native-maps'
project(':react-native-maps').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-maps/lib/android')
include ':app'

MainApplication.java:

package mx.com.MyApp;

import android.app.Application;
import com.facebook.react.ReactApplication;
import com.reactnativecommunity.asyncstorage.AsyncStoragePackage;
import com.horcrux.svg.SvgPackage;
import com.airbnb.android.react.maps.MapsPackage;
import com.kevinejohn.RNMixpanel.RNMixpanel;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.rt2zz.reactnativecontacts.ReactNativeContacts;
import com.rncustomwebview.CustomWebViewPackage;
import com.kevinresol.react_native_default_preference.RNDefaultPreferencePackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.apsl.versionnumber.RNVersionNumberPackage;
import cl.json.RNSharePackage;
import com.babisoft.ReactNativeLocalization.ReactNativeLocalizationPackage;
import com.ianlin.RNCarrierInfo.RNCarrierInfoPackage;
import com.reactnative.ivpusic.imagepicker.PickerPackage;
import com.zmxv.RNSound.RNSoundPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.facebook.CallbackManager;
import org.reactnative.camera.RNCameraPackage;
import com.rnfs.RNFSPackage;
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;
import io.invertase.firebase.storage.RNFirebaseStoragePackage;
import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private static CallbackManager mCallbackManager = CallbackManager.Factory.create();

  protected static CallbackManager getCallbackManager() {
    return mCallbackManager;
  }

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
              new MainReactPackage(),
            new AsyncStoragePackage(),
            new SvgPackage(),
              new MapsPackage(),
              new RNMixpanel(),
              new FBSDKPackage(mCallbackManager),
              new ReactNativeContacts(),
              new CustomWebViewPackage(),
              new RNDefaultPreferencePackage(),
              new RNDeviceInfo(),
              new RNVersionNumberPackage(),
              new RNSharePackage(),
              new ReactNativeLocalizationPackage(),
              new RNFirebaseAnalyticsPackage(),
              new RNCarrierInfoPackage(),
              new PickerPackage(),
              new RNSoundPackage(),
              new RNFirebasePackage(),
              new RNFirebaseMessagingPackage(),
              new RNFirebaseNotificationsPackage(),
              new RNFirebaseStoragePackage(),
              new RNCameraPackage(),
              new RNFSPackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="mx.com.MyApp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:name=".MainApplication"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/AppTheme">

        <provider
            android:authorities="${applicationId}.fileprovider"
            android:name="mx.com.MyApp.UploadFileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider_paths" />
        </provider>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_launcher" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@android:color/black" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="MyApp chanal" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyD0dXBRwVfMjdKr2b_EDzh-tkkzhxPd0Xw"/>

        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

        <activity
            android:name=".MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

        <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

        <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

    </application>

</manifest>


Environment

Click To Expand

react-native info output:

info
  React Native Environment Info:
    System:
      OS: macOS 10.14.5
      CPU: (4) x64 Intel(R) Core(TM) i5-6360U CPU @ 2.00GHz
      Memory: 17.64 MB / 8.00 GB
      Shell: 3.2.57 - /bin/bash
    Binaries:
      Node: 10.15.0 - /usr/local/bin/node
      Yarn: 1.16.0 - /usr/local/bin/yarn
      npm: 6.9.0 - /usr/local/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.2, macOS 10.14, tvOS 12.2, watchOS 5.2
      Android SDK:
        API Levels: 23, 25, 26, 27, 28
        Build Tools: 23.0.1, 25.0.3, 28.0.3
        System Images: android-23 | Intel x86 Atom_64, android-23 | Google APIs Intel x86 Atom_64, android-25 | Google APIs Intel x86 Atom
    IDEs:
      Android Studio: 3.4 AI-183.6156.11.34.5522156
      Xcode: 10.2.1/10E1001 - /usr/bin/xcodebuild
    npmPackages:
      react: 16.8.3 => 16.8.3
      react-native: 0.59.8 => 0.59.8
    npmGlobalPackages:
      create-react-native-app: 1.0.0
      react-native-cli: 2.0.1
  • Platform that you’re experiencing the issue on:
    • iOS
    • Android
    • iOS but have not tested behavior on Android
    • Android but have not tested behavior on iOS
    • Both
  • Are you using TypeScript?
    • N

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 1
  • Comments: 28 (11 by maintainers)

Most upvoted comments

Hi there! The whole react-native community will be struggling with the AndroidX transition for a while.

The community came up with a tool called jetifier that offers forwards compatibility from non-AndroidX apps to libraries (like this one) that have implemented AndroidX, by “reverse-jetifying” the source with a call to npx jetify -r so you can use the AndroidX version of the library in your non-AndroidX app, until you migrate.

I’ve tested it on this module and it appears to work (I use react-native-contacts in my app, I’m not just the jetifier maintainer).

I encourage you to migrate to AndroidX, but until then this can help.

When you do migrate to AndroidX you have the opposite problem with other libraries at which point you’d use jetifier in the forward direction with a call to npx jetify.

Please help spread the word so your fellow developers don’t get stuck - app development is hard enough. Cheers!

@morenoh149 @Subway19 @troydaniels @ryannewton this is the fix I’ve found working. Note, this fix only works if you have enabled the AndroidX.

Perform the below modifications:

ContactsManager.java

// import android.support.annotation.NonNull; //Remove this
// import android.support.v4.app.ActivityCompat; //Remove this
import androidx.annotation.NonNull; //<- Add this
import androidx.core.app.ActivityCompat; // <- Add this

ContactsProvider.java

// import android.support.annotation.NonNull; //Remove this
import androidx.annotation.NonNull; // <- Add this

ReactNativeContacts.java

// import android.support.annotation.NonNull; //Remove this
import androidx.annotation.NonNull; // <- Add this

These fixes works like a charm.

This is proving an issue for us as well

it is still not working after migrating androidx. @morenoh149

Here’s the react native info… React Native Environment Info: System: OS: Linux 4.15 Ubuntu 18.04.2 LTS (Bionic Beaver) CPU: (4) x64 Intel® Core™ i3-2330M CPU @ 2.20GHz Memory: 398.24 MB / 7.70 GB Shell: 4.4.19 - /bin/bash Binaries: Node: 11.2.0 - /usr/local/bin/node Yarn: 1.12.3 - /usr/local/bin/yarn npm: 6.9.0 - /usr/local/bin/npm SDKs: Android SDK: API Levels: 17, 23, 27, 28 Build Tools: 27.0.3, 28.0.3 npmPackages: react: 16.8.3 => 16.8.3 react-native: 0.59.9 => 0.59.9 npmGlobalPackages: create-react-native-app: 2.0.2 react-native-cli: 2.0.1 react-native-git-upgrade: 0.2.7

@ryannewton @morenoh149 @suhanlee l’ve just fixed this issue. This happens when you enabled androidX. It will work fine if you disable it. Else you need to fix the issues by importing the error packages from androidx instead.

this is very odd. I’ll look into this.

Gotcha.

haven’t looked yet