I'm working on a project with another dev and it started happening after I cloned the master branch, all the assets are still there in my project folder under assets/ and I can literally see them by navigating into the folder, but when I run my project (on android only), I cannot see any of the assets being loaded, only white backgrounds. It started happening when the other dev added some productFlavours for different env configurations. Below are some relevant details which I think is related to solving this issue but I cannot seem to do it...
Command I used to run my android project:- npx react-native run-android --variant=DevDebug
My android folder:-
Below is my android/app/build.gradle file:-
apply plugin: "com.android.application"
import com.android.build.OutputFile
project.ext.react = [
enableHermes: (findProperty('expo.jsEngine') ?: "jsc") == "hermes",
cliPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/cli.js",
hermesCommand: new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/%OS-BIN%/hermesc",
composeSourceMapsPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/scripts/compose-source-maps.js",
]
apply from: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../react.gradle")
apply from: new File(["node", "--print", "require.resolve('#sentry/react-native/package.json')"].execute().text.trim(), "../sentry.gradle")
android {
compileSdkVersion rootProject.ext.compileSdkVersion
defaultConfig {
applicationId 'com.myapp'
minSdkVersion rootProject.ext.minSdkVersion
multiDexEnabled true
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 21
versionName "0.2.14"
vectorDrawables.useSupportLibrary = true
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
if (isNewArchitectureEnabled()) {
externalNativeBuild {
ndkBuild {
arguments "APP_PLATFORM=android-21",
"APP_STL=c++_shared",
"NDK_TOOLCHAIN_VERSION=clang",
"GENERATED_SRC_DIR=$buildDir/generated/source",
"PROJECT_BUILD_DIR=$buildDir",
"REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
"REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
"NODE_MODULES_DIR=$rootDir/../node_modules"
cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
cppFlags "-std=c++17"
// Make sure this target name is the same you specify inside the
// src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
targets "myapp-app_appmodules"
}
}
if (!enableSeparateBuildPerCPUArchitecture) {
ndk {
abiFilters (*reactNativeArchitectures())
}
}
}
}
if (isNewArchitectureEnabled()) {
externalNativeBuild {
ndkBuild {
path "$projectDir/src/main/jni/Android.mk"
}
}
def reactAndroidProjectDir = project(':ReactAndroid').projectDir
def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
into("$buildDir/react-ndk/exported")
}
def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
into("$buildDir/react-ndk/exported")
}
afterEvaluate {
preDebugBuild.dependsOn(packageReactNdkDebugLibs)
preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
configureNdkBuildRelease.dependsOn(preReleaseBuild)
configureNdkBuildDebug.dependsOn(preDebugBuild)
reactNativeArchitectures().each { architecture ->
tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
dependsOn("preDebugBuild")
}
tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
dependsOn("preReleaseBuild")
}
}
}
}
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'
}
}
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.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
flavorDimensions "env"
productFlavors {
production {
dimension "env"
applicationId 'com.myapp'
}
development {
dimension "env"
applicationId 'com.myapp'
}
staging {
dimension "env"
applicationId 'com.myapp'
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) {
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
It would really help if someone could provide any solution to this problem, happy to provide any more info if needed!
You can run below command
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
Or
add below code package.json file
"scripts": {
"postinstall": "react-native-fix-image",
}
and then run the commant
npm run postinstall
Related
In the process of upgrading my app from RN v0.68 to RN v0.70 , I ran the npx react-native upgrade command and then start following this guide to finish things up and now my builds start failing after upgrade.
This is the output of my gradlew clean and I get the same error on building app for debug.
FAILURE: Build completed with 2 failures.
1: Task failed with an exception.
-----------
* Where:
Build file 'E:\GitHub\app\android\app\build.gradle' line: 99
* What went wrong:
A problem occurred evaluating project ':app'.
> Cannot invoke method getAbsolutePath() on null object
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================
2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':app'.
> compileSdkVersion is not specified. Please add it to build.gradle
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================
* Get more help at https://help.gradle.org
BUILD FAILED in 9s
5 actionable tasks: 5 up-to-date
this is my app/build.gradle
apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services'
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
import com.android.build.OutputFile
import org.apache.tools.ant.taskdefs.condition.Os
def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()
project.ext.react = [
entryFile: ["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android"].execute(null, rootDir).text.trim(),
enableHermes: true,
cliPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/cli.js",
hermesCommand: new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/%OS-BIN%/hermesc",
composeSourceMapsPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/scripts/compose-source-maps.js",
]
apply from: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../react.gradle")
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds =true
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false);
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
flavorDimensions "default"
productFlavors {
dev {
applicationIdSuffix ".dev"
}
prod {
}
qa {
applicationIdSuffix ".qa"
}
demo{
applicationIdSuffix ".demo"
}
}
defaultConfig {
applicationId "com.employeeapp"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 202212301
versionName "2022.12.30"
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
if (isNewArchitectureEnabled()) {
externalNativeBuild {
cmake {
arguments "-DPROJECT_BUILD_DIR=$buildDir",
"-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
"-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
"-DNODE_MODULES_DIR=$rootDir/../node_modules",
"-DANDROID_STL=c++_shared"
}
}
if (!enableSeparateBuildPerCPUArchitecture) {
ndk {
abiFilters (*reactNativeArchitectures())
// abiFilters "armeabi-v7a","x86"
}
}
}
}
if (isNewArchitectureEnabled()) {
externalNativeBuild {
cmake {
path "$projectDir/src/main/jni/CMakeLists.txt"
}
}
def reactAndroidProjectDir = project(':ReactAndroid').projectDir
def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
into("$buildDir/react-ndk/exported")
}
def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
into("$buildDir/react-ndk/exported")
}
afterEvaluate {
preDebugBuild.dependsOn(packageReactNdkDebugLibs)
preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild)
configureCMakeDebug.dependsOn(preDebugBuild)
reactNativeArchitectures().each { architecture ->
tasks.findByName("configureCMakeDebug[${architecture}]")?.configure {
dependsOn("preDebugBuild")
}
tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure {
dependsOn("preReleaseBuild")
}
}
}
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include (*reactNativeArchitectures())
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword project.env.get("DEBUG_STORE_PASSWORD")
keyAlias project.env.get("DEBUG_KEY_ALIAS")
keyPassword project.env.get("DEBUG_KEY_PASSWORD")
}
release {
storeFile file('unipe.keystore')
storePassword project.env.get("STORE_PASSWORD")
keyAlias project.env.get("KEY_ALIAS")
keyPassword project.env.get("KEY_PASSWORD")
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
signingConfig signingConfigs.release
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) {
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop ->
def options = (findProperty("android.packagingOptions.$prop") ?: "").split(",");
for (i in 0..<options.size()) options[i] = options[i].trim();
options -= ""
if (options.length > 0) {
println "android.packagingOptions.$prop += $options ($options.length)"
options.each {
android.packagingOptions[prop] += it
}
}
}
dependencies {
def appCenterSdkVersion = '4.1.0'
implementation "com.microsoft.appcenter:appcenter-distribute:${appCenterSdkVersion}"
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.work:work-runtime-ktx:2.8.0-alpha01'
implementation "com.facebook.react:react-native:+" // From node_modules
implementation project(':react-native-splash-screen')
implementation 'com.facebook.fresco:fresco:2.0.0'
implementation 'com.facebook.fresco:animated-gif:2.6.0'
implementation 'com.google.firebase:firebase-analytics:17.3.0'
implementation project(':react-native-push-notification')
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
implementation("com.facebook.react:hermes-engine:+") {
exclude group:'com.facebook.fbjni'
}
} else {
implementation jscFlavor
}
}
if (isNewArchitectureEnabled()) {
configurations.all {
resolutionStrategy.dependencySubstitution {
substitute(module("com.facebook.react:react-native"))
.using(project(":ReactAndroid"))
.because("On New Architecture we're building React Native from source")
substitute(module("com.facebook.react:hermes-engine"))
.using(project(":ReactAndroid:hermes-engine"))
.because("On New Architecture we're building Hermes from source")
}
}
}
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.implementation
into 'libs'
}
apply from: new File(["node", "--print", "require.resolve('#react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
applyNativeModulesAppBuildGradle(project)
def isNewArchitectureEnabled() {
return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}
Was upgrading from RN v0.68 to RN v0.70 and had to make some manual code changes for the update , post update the app fails to build. Tried this solution to no avail.
I am upgrading React Native app from 0.68.2 to 0.70.1 with gradle 7.3.3. The npx react-native upgrade ran successfully. Then I enabled new architecture by following RN doc. However npx react-native run-android throws error about an existing applicationVariants.all {...} in android/app/build.gradle:
error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/macair/Documents/code/js/xyz_app6/android/app/build.gradle' line: 315
* What went wrong:
Could not compile build file '/Users/macair/Documents/code/js/xyz_app6/android/app/build.gradle'.
> startup failed:
build file '/Users/macair/Documents/code/js/xyz_app6/android/app/build.gradle': 315: Unexpected input: '{ variant ->\n variant.outputs.each { output ->\n // For each separate APK per architecture, set a unique version code as described here:\n // https://developer.android.com/studio/build/configure-apk-splits.html\n // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.\n def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]\n def abi = output.getFilter(OutputFile.ABI)\n if (abi != null) { // null for the universal-debug, universal-release variants\n output.versionCodeOverride =\n defaultConfig.versionCode * 1000 + versionCodes.get(abi)\n }\n\n }\n }\n}' # line 315, column 1.
}
^
1 error
Here is the android/app/build.gradle. The block causing error is marked out before dependencies {...}:
apply plugin: "com.android.application"
import com.android.build.OutputFile
import org.apache.tools.ant.taskdefs.condition.Os
project.ext.react = [
enableHermes: true, // clean and rebuild if changing //RN 0.70
]
apply from: "../../node_modules/react-native/react.gradle"
//for react-native-code-push
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
//for react-native-vector-icons
apply from: "../../node_modules/react-native-vector-icons/fonts.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
/**
* The preferred build flavor of JavaScriptCore.
*
* 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:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and that value will be read here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", true); //default true for 0.70
/**
* Architectures to build native code for.
*/
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
// RN 0.70
def reactAndroidProjectDir = project(':ReactAndroid').projectDir
def packageReactNdkLibs = tasks.register("packageReactNdkLibs", Copy) {
dependsOn(":ReactAndroid:packageReactNdkLibsForBuck")
dependsOn("generateCodegenArtifactsFromSchema")
from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
into("$buildDir/react-ndk/exported")
}
afterEvaluate {
preBuild.dependsOn(packageReactNdkLibs)
configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild)
configureCMakeDebug.dependsOn(preDebugBuild)
}
packagingOptions {
pickFirst '**/libhermes.so'
pickFirst '**/libjsc.so'
}
// above RN 0.70
defaultConfig {
applicationId "com.xyz_app6"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
// Add this block RN 0.70
externalNativeBuild {
cmake {
arguments "-DPROJECT_BUILD_DIR=$buildDir",
"-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
"-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
"-DNODE_MODULES_DIR=$rootDir/../node_modules",
"-DANDROID_STL=c++_shared"
}
}
}
// Add this block RN 0.70
externalNativeBuild {
cmake {
path "$projectDir/src/main/jni/CMakeLists.txt"
}
}
if (isNewArchitectureEnabled()) {
// We configure the NDK build only if you decide to opt-in for the New Architecture.
externalNativeBuild {
ndkBuild {
arguments "APP_PLATFORM=android-21",
"APP_STL=c++_shared",
"NDK_TOOLCHAIN_VERSION=clang",
"GENERATED_SRC_DIR=$buildDir/generated/source",
"PROJECT_BUILD_DIR=$buildDir",
"REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
"REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build"
cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
cppFlags "-std=c++17"
// Make sure this target name is the same you specify inside the
// src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
targets "xyz_app6_appmodules"
// Fix for windows limit on number of character in file paths and in command lines
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
arguments "NDK_APP_SHORT_COMMANDS=true"
}
}
}
if (!enableSeparateBuildPerCPUArchitecture) {
ndk {
abiFilters (*reactNativeArchitectures())
}
}
}
}
if (isNewArchitectureEnabled()) {
// We configure the NDK build only if you decide to opt-in for the New Architecture.
externalNativeBuild {
ndkBuild {
path "$projectDir/src/main/jni/Android.mk"
}
}
def reactAndroidProjectDir = project(':ReactAndroid').projectDir
def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
into("$buildDir/react-ndk/exported")
}
def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
into("$buildDir/react-ndk/exported")
}
afterEvaluate {
// If you wish to add a custom TurboModule or component locally,
// you should uncomment this line.
// preBuild.dependsOn("generateCodegenArtifactsFromSchema")
preDebugBuild.dependsOn(packageReactNdkDebugLibs)
preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
// Due to a bug inside AGP, we have to explicitly set a dependency
// between configureNdkBuild* tasks and the preBuild tasks.
// This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
configureNdkBuildRelease.dependsOn(preReleaseBuild)
configureNdkBuildDebug.dependsOn(preDebugBuild)
reactNativeArchitectures().each { architecture ->
tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
dependsOn("preDebugBuild")
}
tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
dependsOn("preReleaseBuild")
}
}
}
}
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'
}
//for apk creation
release {
storeFile file(MYAPP_UPLOAD_STORE_FILE)
storePassword MYAPP_UPLOAD_STORE_PASSWORD
keyAlias MYAPP_UPLOAD_KEY_ALIAS
keyPassword MYAPP_UPLOAD_KEY_PASSWORD
}
}
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.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
//for apk creation
signingConfig signingConfigs.release
}
}
//<<===== block below causing error=================================
// 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 {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
//implementation "com.facebook.react:react-native:+" // From node_modules //removed RN 0.70
implementation project(":ReactAndroid") // From node_modules //RN 0.70
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
//def hermesPath = "../../node_modules/hermes-engine/android/"; //removed RN 0.70
//debugImplementation files(hermesPath + "hermes-debug.aar")
//releaseImplementation files(hermesPath + "hermes-release.aar")
//noinspection GradleDynamicVersion. RN 0.70
implementation("com.facebook.react:hermes-engine:+") { // From node_modules
exclude group:'com.facebook.fbjni'
}
} else {
implementation jscFlavor
}
}
//for new architecture RN 0.70
configurations.all {
resolutionStrategy.dependencySubstitution {
substitute(module("com.facebook.react:react-native"))
.using(project(":ReactAndroid"))
.because("On New Architecture we're building React Native from source")
substitute(module("com.facebook.react:hermes-engine"))
.using(project(":ReactAndroid:hermes-engine"))
.because("On New Architecture we're building Hermes from source")
}
}
if (isNewArchitectureEnabled()) {
// If new architecture is enabled, we let you build RN from source
// Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
// This will be applied to all the imported transtitive dependency.
configurations.all {
resolutionStrategy.dependencySubstitution {
substitute(module("com.facebook.react:react-native"))
.using(project(":ReactAndroid")).because("On New Architecture we're building React Native from source")
}
}
}
// 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.implementation
into 'libs'
}
//RN 0.70
def isNewArchitectureEnabled() {
// To opt-in for the New Architecture, you can either:
// - Set `newArchEnabled` to true inside the `gradle.properties` file
// - Invoke gradle with `-newArchEnabled=true`
// - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}
apply from: file("../../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
I've added Material Design Paper library by their manual.
And Gradle prints a lot of warnings as below:
> Task :app:stripDebugDebugSymbols
Execution optimizations have been disabled for task ':app:stripDebugDebugSymbols' to ensure correctness due to the following reasons:
- Gradle detected a problem with the following location: '/app/android/app/build/intermediates/merged_native_libs/debug/out'. Reason: Task ':app:stripDebugDebugSymbols' uses this output of task ':app:copyDebugReactNativeVectorIconFonts' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.2/userguide/validation_problems.html#implicit_dependency for more details about this problem.
If run my app by Android Studio it launches but icons look weirdly (not like here):
android/build.gradle:
buildscript {
ext {
buildToolsVersion = "32.1.0-rc1"
minSdkVersion = 30
compileSdkVersion = 32
targetSdkVersion = 32
ndkVersion = "21.4.7075529"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath('com.android.tools.build:gradle:7.1.1')
}
}
allprojects {
repositories {
maven {
url("$rootDir/../node_modules/react-native/android")
}
maven {
url("$rootDir/../node_modules/jsc-android/dist")
}
mavenCentral {
content {
excludeGroup "com.facebook.react"
}
}
google()
maven { url 'https://www.jitpack.io' }
}
}
android/app/build.gradle:
project.ext.react = [
enableHermes: false,
]
apply from: "../../node_modules/react-native/react.gradle"
apply from: file("../../node_modules/#react-native-community/cli-platform-android/native_modules.gradle")
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
applyNativeModulesAppBuildGradle(project)
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false)
def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")
android {
ndkVersion rootProject.ext.ndkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "com.company.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 4
versionName "0.2.1"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
if (nativeArchitectures) {
ndk {
abiFilters nativeArchitectures.split(',')
}
}
}
release {
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(com.android.build.OutputFile.ABI)
if (abi != null) {
output.versionCodeOverride =
defaultConfig.versionCode * 1000 + versionCodes.get(abi)
}
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'com.facebook.react:react-native:0.67.2' // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
debugImplementation('com.facebook.flipper:flipper:0.131.1') {
exclude group:'com.facebook.fbjni'
}
debugImplementation('com.facebook.flipper:flipper-network-plugin:0.131.1') {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation('com.facebook.flipper:flipper-fresco-plugin:0.131.1') {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/"
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.implementation
into 'libs'
}
android/settings.gradle:
rootProject.name = 'App'
apply from: file("../node_modules/#react-native-community/cli-platform-android/native_modules.gradle")
applyNativeModulesSettingsGradle(settings)
include ':app'
Where can the problem be?
I was facing the same problem and solving the issue just putting the line
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
on the file build.gradle under android/app/build.gradle then build again.
And finally, the icons are shown correctly as well.
Finally, I've found a solution. I was needed to copy these fonts into
android/app/src/main/assets/fonts
Although it's still weird for me because I thought this process will be completed automatically on build.
I am new to react native--new to app development in general in fact. I am trying to run a release build on Android emulator but the app just keeps crashing.
The debug version runs without any problem, and on iOS the same release build runs perfectly.
Here are what I did:
1.Cleaned the build folder
2.Created index.android.bundle at android/app/src/main/assets
3.Created release APK file
4.Ran on Android simulator, but keeps crashing.
I am lost here. Could someone help out and tell me where I possibly went wrong?
Here is by android/app/build.gradle:
import com.android.build.OutputFile
apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services'
project.ext.react = [
enableHermes: false
]
apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = true
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false);
//Function to get key from the key store
def getPassword(String currentUser, String keyChain) {
def stdout = new ByteArrayOutputStream()
def stderr = new ByteArrayOutputStream()
exec {
commandLine 'security', '-q', 'find-generic-password', '-a', currentUser, '-s', keyChain, '-w'
standardOutput = stdout
errorOutput = stderr
ignoreExitValue true
}
//noinspection GroovyAssignabilityCheck
stdout.toString().trim()
}
def pass = getPassword("my_name","my_keystore");
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.myappid"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
multiDexEnabled true
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"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
release {
storeFile file('release.keystore')
storePassword pass
keyAlias 'release'
keyPassword pass
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.release
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
shrinkResources true
}
}
packagingOptions {
pickFirst "lib/armeabi-v7a/libc++_shared.so"
pickFirst "lib/arm64-v8a/libc++_shared.so"
pickFirst "lib/x86/libc++_shared.so"
pickFirst "lib/x86_64/libc++_shared.so"
}
dexOptions {
javaMaxHeapSize "4g"
}
// 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
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 fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
implementation 'com.google.firebase:firebase-core:17.0.0'
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
addUnimodulesDependencies([exclude: ['expo-splash-screen','expo-permissions']])
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// 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 from: file("../../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
Here is the error log from adb logcat:
It seems like your issue from your error log is related to this...
React-Native :java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so
Open Build.gradle from android/app.
Change enableProguardInReleaseBuilds to false,
def enableProguardInReleaseBuilds = false
clean the gradle and try
I have an android studio project, and I'm trying to port gradle from the stable version 2.0.0 to the experimental version 0.7.0-beta1:
This is the working code inside my android tag module my 2.0.0 gradle code:
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.test.myapp"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
ndk {
moduleName "myNativeLib"
}
}
sourceSets.main {
jniLibs.srcDir 'src/main/libs' //set .so files location to libs
jni.srcDirs = [] //disable automatic ndk-build call
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
task runSwig(type: Exec, description: 'Run swig config') {
workingDir 'src/main'
commandLine 'cmd', '/c', 'swig.bat'
}
Properties props = new Properties()
props.load(new FileInputStream(file(project.property("KeyStore.properties"))))
signingConfigs {
storeSignature {
storeFile = file(props['KEYSTORE'])
storePassword = props['KEYSTORE_PASSWD']
keyAlias = props['KEYSTORE_MYAPP']
keyPassword = props['KEYSTORE_MYAPP_PASSWD']
}
}
buildTypes {
def SERVER_URL = "SERVER_URL"
debug {
debuggable true
jniDebuggable true
buildConfigField "String", SERVER_URL, "\"http://testusound.eastus.cloudapp.azure.com/androidbackend/checkjson\""
versionNameSuffix getMasterName() + "." + getDate()
}
release {
signingConfig signingConfigs.storeSignature
debuggable false
jniDebuggable false
minifyEnabled false
buildConfigField "String", SERVER_URL, "\"http://www.usound.co/androidbackend/checkjson\""
versionNameSuffix getMasterName()
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
Now here is my attempt to rewrite my code for the expermiental pluggin 0.7.0-beta1:
model {
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig.with {
applicationId "com.test.myapp"
minSdkVersion.apiLevel 15
targetSdkVersion.apiLevel 23
versionCode 1
versionName "1.0"
}
ndk {
moduleName "myNativeLib"
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
task runSwig(type: Exec, description: 'Run swig config') {
workingDir 'src/main'
commandLine 'cmd', '/c', 'swig.bat'
}
buildConfigFields.with {
create() {
type "String"
name "SERVER_URL"
value "\"http://www.myserver.com/backend/checkjson\""
}
}
buildConfigFields.with {
create() {
type "String"
name "TEST_SERVER_URL"
value "\"http://www.mytestserver.com/backend/checkjson\""
}
}
sources {
main {
jni {
source {
srcDir "src"
}
}
jni.srcDirs = [] //disable automatic ndk-build call
}
}
buildTypes {
debug {
debuggable true
jniDebuggable true
buildConfigField $("android.buildConfigFields.TEST_SERVER_URL")
versionNameSuffix getMasterName() + "." + getDate()
}
release {
signingConfig = $("android.signingConfigs.mySignature")
debuggable false
jniDebuggable false
minifyEnabled false
buildConfigField $("android.buildConfigFields.SERVER_URL")
versionNameSuffix getMasterName()
proguardFiles.add(file('proguard-rules.pro'))
}
}
Properties props = new Properties()
props.load(new FileInputStream(file(project.property("KeyStore.properties"))))
}
android.signingConfigs {
create("mySignature")
storeFile = file(props['KEYSTORE'])
storePassword = props['KEYSTORE_PASSWD']
keyAlias = props['KEYSTORE_MYAPP']
keyPassword = props['KEYSTORE_MYAPP_PASSWD']
}
}
I'm getting this error error with the signingConfigs:
Error:Attempt to read a write only view of model of type 'java.lang.Object' given to rule 'android.signingConfigs { ... } # app\build.gradle line 165, column 5'
in my code would be this line:
android.signingConfigs {
for my signing configs I'm using a file called keystore.properties located under my main folder (I would like to keep it this way in a separate file so I don't upload my keystore signature data to git, so I haven't put the signing config keys like in the current experimental gradle projects).
What am I missing here? How should I write the signing configs to use properties loaded from a file?
As I'm just getting into experimental gradle feel free to give me some examples or info you believe might be useful.
The stuff after create should be in a set of {}'s
android.signingConfigs {
create("mySignature") { // <-- needed
storeFile = file(props['KEYSTORE'])
storePassword = props['KEYSTORE_PASSWD']
keyAlias = props['KEYSTORE_MYAPP']
keyPassword = props['KEYSTORE_MYAPP_PASSWD']
} // <-- needed
}