wix / react-native-navigation

A complete native navigation solution for React Native
https://wix.github.io/react-native-navigation/
MIT License
13.04k stars 2.67k forks source link

[Android] Auto linker fails on new react-native 0.71.3 project #7695

Closed eaco-andrew closed 1 year ago

eaco-andrew commented 1 year ago

What happened?

Created a new blank React Native project. Installed react-native-navigation Run the auto linker Failed to modify the MainActivity.java & MainApplication.java to a working state

What was the expected behaviour?

That the auto linker would correctly modify MainActivity.java & MainApplication.java to a working state

Was it tested on latest react-native-navigation?

Help us reproduce this issue!

Compile Issues

> Task :app:compileDebugJavaWithJavac FAILED
32 actionable tasks: 2 executed, 30 up-to-date
/Users/person/code/myapp/android/app/src/main/java/com/myapp/MainApplication.java:16: error: cannot find symbol
      new NavigationReactNativeHost(this) {
          ^
  symbol:   class NavigationReactNativeHost
  location: class MainApplication
/Users/person/code/myapp/android/app/src/main/java/com/myapp/MainApplication.java:17: error: method does not override or implement a method from a supertype
        @Override
        ^
/Users/person/code/myapp/android/app/src/main/java/com/myapp/MainApplication.java:22: error: method does not override or implement a method from a supertype
        @Override
        ^
/Users/person/code/myapp/android/app/src/main/java/com/myapp/MainApplication.java:25: error: no suitable constructor found for PackageList(<anonymous NavigationReactNativeHost>)
          List<ReactPackage> packages = new PackageList(this).getPackages();
                                        ^
    constructor PackageList.PackageList(ReactNativeHost) is not applicable
      (argument mismatch; <anonymous NavigationReactNativeHost> cannot be converted to ReactNativeHost)
    constructor PackageList.PackageList(Application) is not applicable
      (argument mismatch; <anonymous NavigationReactNativeHost> cannot be converted to Application)
/Users/person/code/myapp/android/app/src/main/java/com/myapp/MainApplication.java:31: error: method does not override or implement a method from a supertype
        @Override
        ^
/Users/person/code/myapp/android/app/src/main/java/com/myapp/MainApplication.java:36: error: method does not override or implement a method from a supertype
        @Override
        ^
/Users/person/code/myapp/android/app/src/main/java/com/myapp/MainApplication.java:41: error: method does not override or implement a method from a supertype
        @Override
        ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
7 errors

Here are my MainApplication & MainActivity. Any that can help correct configure them would be awesome.

MainApplication.java

package com.myapp;

import android.app.Application;
import com.facebook.react.PackageList;
import com.reactnativenavigation.NavigationApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactNativeHost;
import com.facebook.soloader.SoLoader;
import java.util.List;

public class MainApplication extends NavigationApplication {

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

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          // packages.add(new MyReactNativePackage());
          return packages;
        }

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

        @Override
        protected boolean isNewArchEnabled() {
          return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
        }

        @Override
        protected Boolean isHermesEnabled() {
          return BuildConfig.IS_HERMES_ENABLED;
        }
      };

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

  @Override
  public void onCreate() {
    super.onCreate();

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
      // If you opted-in for the New Architecture, we load the native entry point for this app.
      DefaultNewArchitectureEntryPoint.load();
    }
    ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
  }
}

MainActivity.java

package com.myapp;

import com.reactnativenavigation.NavigationActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactActivityDelegate;

public class MainActivity extends NavigationActivity {

  /**
   * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link
   * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React
   * (aka React 18) with two boolean flags.
   */
}

In what environment did this happen?

React Native Navigation version: 7.32.1 React Native version: 0.71.3 Has Fabric (React Native's new rendering system) enabled: yes Node version: 16.14.2 Device model: sdk_gphone64_arm64 Android version: 13

1fabiopereira commented 1 year ago

I have the same problem 👀.

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If you believe the issue is still relevant, please test on the latest version and report back. Thank you for your contributions.

fernandopontue commented 1 year ago

Here as well.

Fresh react install

williamgurzoni commented 1 year ago

I'm having the same issue when trying to upgrade to RN 0.71.7 and Navigation 7.32.1.

MatthewPattell commented 1 year ago

Any chance run RN 0.71.7 and Navigation 7.32.1?

MainApplication.java

package com.test.app;

import com.facebook.react.PackageList;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import java.util.List;

import com.reactnativenavigation.NavigationApplication;
import com.reactnativenavigation.react.NavigationReactNativeHost;
import com.microsoft.codepush.react.CodePush;
import com.facebook.react.bridge.JSIModulePackage;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;
import com.mobile.ReactNativeFlipper;

public class MainApplication extends NavigationApplication {

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

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          return packages;
        }

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

        @Override
        protected JSIModulePackage getJSIModulePackage() {
          return new ReanimatedJSIModulePackage();
        }

        @Override
        protected String getJSBundleFile() {
            return CodePush.getJSBundleFile();
        }
      };

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

  @Override
  public void onCreate() {
    super.onCreate();

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
      // If you opted-in for the New Architecture, we load the native entry point for this app.
      DefaultNewArchitectureEntryPoint.load();
    }
    ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
  }
}

MainActivity.java

package com.test.app;

import com.reactnativenavigation.NavigationActivity;
import com.zoontek.rnbootsplash.RNBootSplash;
import android.os.Bundle;

public class MainActivity extends NavigationActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    RNBootSplash.init(R.drawable.splashscreen, MainActivity.this);
  }
}

android/app/build.gradle

apply plugin: "com.android.application"
apply plugin: "com.facebook.react"

import com.android.build.OutputFile

/**
 * This is the configuration block to customize your React Native Android app.
 * By default you don't need to apply any configuration, just uncomment the lines you need.
 */
react {
    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '..'
    // root = file("../")
    //   The folder where the react-native NPM package is. Default is ../node_modules/react-native
    // reactNativeDir = file("../node_modules/react-native")
    //   The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen
    // codegenDir = file("../node_modules/react-native-codegen")
    //   The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
    // cliFile = file("../node_modules/react-native/cli.js")
    /* Variants */
    //   The list of variants to that are debuggable. For those we're going to
    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
    // debuggableVariants = ["liteDebug", "prodDebug"]
    /* Bundling */
    //   A list containing the node command and its flags. Default is just 'node'.
    nodeExecutableAndArgs = ["node", "--max-old-space-size=4096"]
    //
    //   The command to run when bundling. By default is 'bundle'
    // bundleCommand = "ram-bundle"
    //
    //   The path to the CLI configuration file. Default is empty.
    // bundleConfig = file(../rn-cli.config.js)
    //
    //   The name of the generated asset file containing your JS bundle
    // bundleAssetName = "MyApplication.android.bundle"
    //
    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
    // entryFile = file("../js/MyApplication.android.js")
    //
    //   A list of extra flags to pass to the 'bundle' commands.
    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
    // extraPackagerArgs = []
    /* Hermes Commands */
    //   The hermes compiler command to run. By default it is 'hermesc'
    // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    // hermesFlags = ["-O", "-output-source-map"]
}

/**
 * Set this to true to create four separate APKs instead of one,
 * one for each native architecture. This is useful if you don't
 * use App Bundles (https://developer.android.com/guide/app-bundle/)
 * and want to have separate APKs to upload to the Play Store.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US. Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Private function to get the list of Native Architectures you want to build.
 * This reads the value from reactNativeArchitectures in your gradle.properties
 * file and works together with the --active-arch-only flag of react-native run-android.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion
    namespace "com.test.app"

    defaultConfig {
        applicationId "com.test.app"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode project.getProperties().get("versionCode", 1).toInteger()
        versionName project.getProperties().get("versionName", "1.0.0")
        missingDimensionStrategy "store", "play"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        release {
          storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            firebaseCrashlytics {
                nativeSymbolUploadEnabled true
                unstrippedNativeLibsDir 'build/intermediates/merged_native_libs/release/out/lib'
            }
        }
    }

    // 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:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
            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 =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")
    implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0")

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}")

    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"

gradle.properties

org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=1024m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
android.useAndroidX=true
android.enableJetifier=true
FLIPPER_VERSION=0.125.0
reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
newArchEnabled=false
hermesEnabled=false

App build success, but crash when launching:

with hermesEnabled=true

E/SoLoader: couldn't find DSO to load: libhermes.so
...
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.test.app, PID: 18021
    java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so
        SoSource 0: com.facebook.soloader.ApkSoSource[root = /data/data/com.test.app/lib-main flags = 1]
        SoSource 1: com.facebook.soloader.DirectorySoSource[root = /data/app/com.test.app-EPmsRDeeQr9SKWZrh0FvQA==/lib/x86 flags = 0]
        SoSource 2: com.facebook.soloader.DirectorySoSource[root = /vendor/lib flags = 2]
        SoSource 3: com.facebook.soloader.DirectorySoSource[root = /system/lib flags = 2]
        Native lib dir: /data/app/com.test.app-EPmsRDeeQr9SKWZrh0FvQA==/lib/x86
     result: 0

with hermesEnabled=false

E/unknown:com.facebook.react.uimanager.UIManagerHelper: Unhandled SoftException
    com.facebook.react.bridge.ReactNoCrashSoftException: Cannot get UIManager because the context doesn't contain an active CatalystInstance.
        at com.facebook.react.uimanager.UIManagerHelper.getUIManager(UIManagerHelper.java:77)
        at com.facebook.react.uimanager.UIManagerHelper.getUIManager(UIManagerHelper.java:47)
        at com.facebook.react.ReactInstanceManager.attachRootViewToInstance(ReactInstanceManager.java:1241)
        at com.facebook.react.ReactInstanceManager.attachRootView(ReactInstanceManager.java:890)
        at com.facebook.react.ReactRootView.attachToReactInstanceManager(ReactRootView.java:822)
        at com.facebook.react.ReactRootView.onMeasure(ReactRootView.java:183)
        at com.reactnativenavigation.react.ReactView.onMeasure(Unknown Source:10)
        at android.view.View.measure(View.java:24530)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        ....

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.test.app, PID: 17362
    java.lang.IllegalStateException: Unable to attach a rootView to ReactInstance when UIManager is not properly initialized.
        at com.facebook.react.ReactInstanceManager.attachRootViewToInstance(ReactInstanceManager.java:1245)
        at com.facebook.react.ReactInstanceManager.attachRootView(ReactInstanceManager.java:890)
        at com.facebook.react.ReactRootView.attachToReactInstanceManager(ReactRootView.java:822)
        at com.facebook.react.ReactRootView.onMeasure(ReactRootView.java:183)
        at com.reactnativenavigation.react.ReactView.onMeasure(Unknown Source:10)
        at android.view.View.measure(View.java:24530)
        ........

any help to fix it?

UPDATED: After a few minutes, I found out that the problem is in third-party libraries. Navigation working... but without hermes

williamgurzoni commented 1 year ago

Update: I was able to get it working (with Hermes) by removing the @Override, as I believe the Navigation is not implementing those functions yet.


// @Override <---
protected boolean isNewArchEnabled() {
  return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
}

// @Override <---
protected Boolean isHermesEnabled() {
  return BuildConfig.IS_HERMES_ENABLED;
}
MatthewPattell commented 1 year ago

Update: I was able to get it working (with Hermes) by removing the @Override, as I believe the Navigation is not implementing those functions yet.

// @Override <---
protected boolean isNewArchEnabled() {
  return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
}

// @Override <---
protected Boolean isHermesEnabled() {
  return BuildConfig.IS_HERMES_ENABLED;
}

in my case with config above and this functions I still getting error:

E/SoLoader: couldn't find DSO to load: libhermes.so

UPDATED: I managed to launch with Hermes, the problem was that I did not delete the line at the end of the file android/app/build.gradle

apply from: "../../node_modules/react-native/react.gradle" // remove this
williamgurzoni commented 1 year ago

@MatthewPattell As part of the installation, the docs says to comment the SoLoader. Did you do that? See image:

Screenshot 2023-05-12 at 10 39 36 AM
MatthewPattell commented 1 year ago

@williamgurzoni yes

I launched android, see update part

thanks

gusilveiramp commented 1 year ago

Same here! Any update?