React-native: [Android] Requiring images with Gradle 4 fails release builds

Created on 21 Nov 2017  路  122Comments  路  Source: facebook/react-native

Hello guys,

I ran into this issue when updating Gradle and Android Studio.

Thanks for your help!

Is this a bug report?

Yes

Have you read the Contributing Guidelines?

Yes

Environment

Environment:
OS: macOS Sierra 10.12.6
Node: 8.5.0
Yarn: 1.3.2
npm: 5.3.0
Watchman: 4.7.0
Xcode: Xcode 9.1 Build version 9B55
Android Studio: 3.0 AI-171.4408382

Packages: (wanted => installed)
react: 16.0.0 => 16.0.0
react-native: 0.50.3 => 0.50.3

Target Platform: Android (22)

Steps to Reproduce

Requiring images with latest gradle fails release builds

I created a small test project but here are the steps to reproduce it:

  1. Init a new project: react-native init Test
  2. Update to latest Gradle:

    • Open Android Studio and install recommended version

    • Build from Android Studio, it should ask you to update build tools, do so

  3. Require an image in index.js
  4. Run cd android && ./gradlew assembleRelease

Expected Behavior

The command ./gradlew assembleRelease should not fail

Actual Behavior

Running ./gradlew assembleRelease when the image is required from the JS fails with:

/Users/almouro/bam/uefa/TestGradle3/android/app/build/intermediates/res/merged/release/drawable-mdpi/image.png: error: uncompiled PNG file passed as argument. Must be compiled first into .flat file..
error: failed parsing overlays.

If the image is not required, the command works fine.

Reproducible Demo

git clone https://github.com/Almouro/react-native-with-gradle-4
yarn
cd android
./gradlew assembleRelease

Workaround

Adding android.enableAapt2=false to android/gradle.properties fixes the issue but it is only a workaround.

Regression Author Provided Repro Android Ran Commands Fixed Locked

Most helpful comment

This bug has been a pain since we've upgraded to Android 3.x and setting android.enableAapt2 = false is not a sustainable long term workaround. It's disappointing that there is no traction on this serious issue.

All 122 comments

I have the same issue

+1 馃槀

+1 have same issue with react-native 0.50
setting android.enableAapt2=false to android/gradle.properties
helps with this issue. However, I am running into a next problem (and not sure if this due to the above setting).

  Task :app:bundleReleaseJsAndAssets
 Scanning folders for symlinks in /home/v/devel/mine/proj/mob/rn.common/node_modules (12ms)
 Scanning folders for symlinks in /home/v/devel/mine/proj/mob/rn.common/node_modules (10ms)
 Loading dependency graph, done.
 warning: the transform cache was reset.
 bundle: start
 bundle: finish
 bundle: Writing bundle output to: /home/v/tmp/u1b/app/intermediates/assets/release/index.android.bundle
 bundle: Done writing bundle output
 bundle: Copying 18 asset files
 bundle: Done copying assets

/home/v/tmp/u1b/app/intermediates/res/merged/release/drawable-mdpi/src_jsapp_img_material_ic_local_library_black_48dp_android_drawablexxhdpi_ic_local_library_black_48dp.png: error: Invalid filename.  Unable to add.


The file

/home/v/tmp/u1b/app/intermediates/res/merged/release/drawable-mdpi/src_jsapp_img_material_ic_local_library_black_48dp_android_drawablexxhdpi_ic_local_library_black_48dp.png

indeed, is not present in the merged/release directory. But I have no idea who generates that file name for what reason/etc.

My understanding is that the React Native bundleJS gradle task copies all the images in the android merged resources folder, but aapt now expects images there to be compiled in .flat files.

@Almouro I sorted out the issue with
src_jsapp_img_material_ic_local_library_black_48dp_android_drawablexxhdpi_ic_local_library_black_48dp.png

it turns out that something in aapt (or somewhere in gradle) chokes on image file names that are located in deep directory structures.
The above name was created by concatenating (with '_') the directory tree where local_library_black_48dp.png was. I basically moved the file into a simpler directory structure, then updated my require ('path_to_image/..) in my index.android.js and that particular problem went away

the need to do the android.enableAapt2=false workaround is still there, unfortunately

Same error:

Scanning 766 folders for symlinks in /Users/waltermonecke/Code_Projects/reactNative/lisdo/node_modules (15ms)
Scanning 766 folders for symlinks in /Users/waltermonecke/Code_Projects/reactNative/lisdo/node_modules (100ms)
Loading dependency graph, done.
warning: the transform cache was reset.
bundle: start
bundle: finish
bundle: Writing bundle output to: /Users/waltermonecke/Code_Projects/reactNative/lisdo/android/app/build/intermediates/assets/release/index.android.bundle
bundle: Done writing bundle output
bundle: Copying 106 asset files
bundle: Done copying assets

/Users/waltermonecke/Code_Projects/reactNative/lisdo/android/app/build/intermediates/res/merged/release/drawable-hdpi/node_modules_reactnativerouterflux_node_modules_reactnavigation_src_views_assets_backicon.png: error: uncompiled PNG file passed as argument. Must be compiled first into .flat file..
error: failed parsing overlays.

node_modules:
"react": "16.0.0-alpha.12",
"react-native": "0.48.3",

Has anyone had any success fixing this? I can't test the production app because of this.

I have the same issue;
also happens on production builds. :(

I have the same issue

I have the same issue

I have the same issue.
I Adding android.enableAapt2=false to android/gradle.properties
but no effect.

This bug has been a pain since we've upgraded to Android 3.x and setting android.enableAapt2 = false is not a sustainable long term workaround. It's disappointing that there is no traction on this serious issue.

I have the same issue

Can't use android.enableAapt2=false since then other necessary components fail. A bad situation to find this near the end of a project.

Same getting similar issue.

android.enableAapt2=false works (when there are no images in drawable)

Getting the same issue :(

Sorry to ask again, but is there a way to deal with this issue? If I do Debug it would be okay, but choose Release Mode and this happens. Thanks

+1

any idea of how to fix this?

  1. Delete the tmp files of the images that were created during the build process. (in tmp\YOURAPPappintermediates\res\merged\release\drawable....). The exact path is given by the compiler error.
  2. Search for files that have a @-suffix different from @2x or @3x in your app folder and delete them. See https://facebook.github.io/react-native/docs/images.html
  3. Sometimes the issue stems from images of a module you use. Search for the images with wrong suffix in the respective node_modules folder and delete them.
  4. DON'T USE the common workaround (which consists in disabling aapt2).

tl;dr - I think the bundling step in react.gradle should hand off to the Android build system much earlier in the build process

I may have killed a few birds with one stone while working out a solution for something unrelated.

I wanted to bundle the js ahead of time, then build multiple variants using that same bundle. The solution I came up with also allows you to keep AAPT2 enabled, which was a major plus.

First I set a few environment variables, REACT_NATIVE_JS_DIR and REACT_NATIVE_ASSETS_DIR.

Then I bundle with --bundle-output "$REACT_NATIVE_JS_DIR/index.android.bundle" --assets-dest "$REACT_NATIVE_ASSETS_DIR".

The build.gradle adds those to the main source set:

// not needed anymore in this setup:
// apply from: "../../node_modules/react-native/react.gradle"
android {
    ...
    sourceSets {
        // Android includes "main" in all application variants
        main {
            assets.srcDirs += System.env.REACT_NATIVE_JS_DIR
            res.srcDirs += System.env.REACT_NATIVE_ASSETS_DIR
        }
    }
}

Overall this feels a lot friendlier to the Android build system, as the resources and assets actually go through the merge${VariantName}Assets and merge${VariantName}Resources tasks. As a bonus, my universal APK was even 4% smaller.

I have a feeling that react.gradle could be modified to do something similar, like:

  • Output to "build/generated" instead of "build/intermediates"
  • Append those directories to the source sets like above
  • Make merge${VariantName}Assets and merge${VariantName}Resources depend on the bundling step

    • Currently this is reversed - it requires the merge tasks to happen first, then tries to output to those already-merged (and AAPT2-processed) intermediate directories, with a fair amount of hard-coded paths and build task dependency ordering

I'll try to find some time to put a PR together if that sounds reasonable.

@CFKevinRef I've verified your approach works, as long as REACT_NATIVE_ASSETS_DIR isn't actually pointing to ./android/app/build/intermediates/res/merged/$build_type. This did it for me:

android_intermediates=$(mktemp -d)
export REACT_NATIVE_JS_DIR=$android_intermediates/assets/$build_type_lower
export REACT_NATIVE_ASSETS_DIR=$android_intermediates/res/merged/$build_type_lower

It's not a great long-term solution, though, since avoiding the default gradle support may cause issues down the road, when new behavior is added, or something is changed. For now, it does allow things to work with AAPT2. Thank you!

It'd be great to see that PR and have this ball rolling.

Until this got fixed, there is another workaround similar to solution proposed by @CFKevinRef. This solution also allows you to keep using AAPT2. Workaround consists of three steps

  • change default bundling output folder to be in src/ directory instead of build folder. You can do this by changing react properties at the top of your build.gradle (app build gradle)
ext.react = [
        bundleInRelease        : true,
        resourcesDirRelease   : "src/release/res"
]
apply from: "../react.gradle" /*Check file for more information*/
apply plugin: 'com.android.application'

please note that properties names are dynamic and depends on your target names, bundleIn, resourcesDir

  • Add generated files to git ignore, to keep your native resources folder clean
    android/app/src/*/res/*/reactnative_*.png
    android/app/src/*/res/*/node_modules_*.png
  • Reverse dependency between this react gradle task (bundling) and merging assets and resources.
    This is the hardest part, you need to change this file {project_root_dir}/node_modules/react-native/react.gradle, In my case I copied this file to my project and keep updating it with each react release. The change is quite simple
    replace
currentBundleTask.dependsOn("merge${targetName}Resources")
currentBundleTask.dependsOn("merge${targetName}Assets")

with

runBefore("merge${targetName}Resources", currentBundleTask)
runBefore("merge${targetName}Assets", currentBundleTask)

Please give https://github.com/facebook/react-native/pull/17967 a try. You should be able to just replace your react.gradle with that one.

Also if you have some old projects lying around based on the Android Gradle Plugin 1.x or 2.x I would appreciate a test as well!

I had the same issue. But did not fix with - android.enableAapt2=false, as this has issues with other drawable resources in the project.

Fixed it with adding org.gradle.configureondemand=true in build.gradle, which shall disable the 'bundleReleaseJsAndAssets' task to run, which is the best solution and works in any condition. Hope this helps.

@facebook-github-bot reopen
By using that commit, i get lots of duplicate assets error, like this:

[drawable-xhdpi-v4/app_assets_icons_lock] /Users/XXX/android/app/src/main/res/drawable-xhdpi/app_assets_icons_lock.png
[drawable-xhdpi-v4/app_assets_icons_lock] /Users/XXX/android/app/build/generated/res/react/release/drawable-xhdpi/app_assets_icons_lock.png
: Error: Duplicate resources

LE,
even after deleting duplicate assets from drawable-*, build still fails, with all node-modules depenencies failing like: (after clearing cache, ./gradlew clean, npm install, update react.gradle)

Could not resolve project :react-native-sqlite-storage.
 Required by:
         project :app
      > Unable to find a matching configuration of project :react-native-sqlite-storage:
          - Configuration 'debugApiElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'dev' and found incompatible value 'debug'.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
              - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
              - Required org.gradle.api.attributes.Usage 'java-runtime' and found incompatible value 'java-api'.
          - Configuration 'debugRuntimeElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'dev' and found incompatible value 'debug'.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
              - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
              - Required org.gradle.api.attributes.Usage 'java-runtime' and found compatible value 'java-runtime'.
          - Configuration 'releaseApiElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'dev' and found incompatible value 'release'.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
              - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
              - Required org.gradle.api.attributes.Usage 'java-runtime' and found incompatible value 'java-api'.
          - Configuration 'releaseRuntimeElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'dev' and found incompatible value 'release'.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
              - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
              - Required org.gradle.api.attributes.Usage 'java-runtime' and found compatible value 'java-runtime'.

As for now, I ended up reverting to Android Studio 2.3.3, as it's the latest version which can build the release

@CFKevinRef I am getting the following error from the proposed react.gradle file:

Received result Failure[value=org.gradle.initialization.ReportedException: org.gradle.internal.exceptions.LocationAwareException: Circular dependency between the following tasks:
:app:bundleProductionReleaseJsAndAssets
\--- :app:recordFilesBeforeBundleCommandProductionRelease
     \--- :app:mergeProductionReleaseResources
          \--- :app:bundleProductionReleaseJsAndAssets (*)

Ah ha, this is because CodePush has to do some fairly intricate tracking to generate a hash of "every file created by the react-native bundle task." Their current technique will no longer work as-is.

The good news is that it should be _much_ easier now, as I've exposed the bundle task itself on the application variant, as well the generated lists of files:

android.applicationVariants.all { variant ->
    // This is the generated task itself:
    def reactBundleTask = variant.bundleJsAndAssets
    // These are the outputs by type:
    def resFileCollection = reactBundleTask.generatedResFolders
    def assetsFileCollection = reactBundleTask.generatedAssetsFolders
}

It's possible to test for this new behavior by checking for the bundleJsAndAssets property on application variants.

In any case, as this is merged now, that is probably an issue to fix over at https://github.com/Microsoft/react-native-code-push/

@CFKevinRef Thanks for the feedback and the great work. For those also seeing this thread, I reverted to Android Studio 2.3.3 to wait for this to settle out, which was pretty painless. I will ensure a bug is exists with codepush and reference the appropriate RN issue(s).

Hello guys, I have the same issue and so is there a solution for that problem.

@hramos could we reopen this? As far as I can tell no fix has been made - a PR was merged then reverted so this is still a problem.

I tried the following steps to solve this issue:

  • remove src/res/drawable-xxx directory
  • add this configuration to gradle.properties
  • Make sure enableProguardInReleaseBuilds is false

@Xing-He I don't know anything about gradle. But using your solution create another error which is duplicate files error. And using the stackoverflow solution (see link) create another error :

To run dex in process, the Gradle daemon needs a larger heap.
It currently has 1024 MB.

脭.脭

And about the @CFKevinRef solution, what are the values to set for REACT_NATIVE_JS_DIR and REACT_NATIVE_ASSETS_DIR?

Any news about this error?

Also getting this error when trying to package up the bundle for a React Native component within an Android project.

Edit: Discovered my config was wrong for packaging up the bundle.

For anyone experiencing dex related errors try this inside of your android/app/build.gradle

android {
    ...
    dexOptions {
        jumboMode true
    }
}

Related: https://developers.soundcloud.com/blog/congratulations-you-have-a-lot-of-code-remedying-androids-method-limit-part-1

@CFKevinRef your PR #17967 worked for me with gradle-4.6 and gradle plugin 3.0.1. This was critical for me since I use react-native-maps which demands an upgraded gradle. I think react-native needs to upgrade its gradle, but I don't know what the impact of third party libraries is.

Thank you very much for this. One question: How should we keep the private version of react.gradle up to date as new versions of react-native are released?

This was critical for me since I use react-native-maps which demands an upgraded gradle. I think react-native needs to upgrade its gradle, but I don't know what the impact of third party libraries is.

I'm not sure if React Native needs to upgrade its gradle version, React Native Maps did because it was causing build issues within Android Studio 3.0+ whenever I was using it, so I put in a PR to update it.

The reason why RN-Maps was throwing an issue during build is because React Native Maps is added as a Java module which produces a build.gradle file for the module in your project and so AS checks the gradle file for it. Before I added the PR, it kept throwing issues which was always fixed whenever I updated the gradle keywords within the RN-Maps project.

Thanks @IljaDaderko I was having a dex exception but adding that fixed it!!! Only spent 3 hours pulling out my hair :)

@ujwal-setlur I need to see if I can fix the PR to work with a build-from-source of React Native.

Sounds good. Happy to test it when ready.

Just found that issue. Having the same problem, only disable aapt2 fixed it.

Looking forward to see if you can get it working @CFKevinRef

With the workaround applied (android.enableAapt2=false) not only will android gradle build spit countless warnings
```WARNING: The option 'android.enableAapt2' is deprecated and should not be used anymore.
Use 'android.enableAapt2=true' to remove this warning.
It will be removed at the end of 2018..

but also my project won't build in Android Studio 3.1+ (it will still build from the terminal).

```Execution failed for task ':UI:transformDexWithInstantRunDependenciesApkForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: Failed to execute aapt

* Try:
Run with --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':UI:transformDexWithInstantRunDependenciesApkForDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:103)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:256)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:249)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:238)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:663)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:597)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: Failed to execute aapt
    at com.android.builder.profile.Recorder$Block.handleException(Recorder.java:55)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:104)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:212)
    at sun.reflect.GeneratedMethodAccessor302.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:124)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:113)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:95)
    ... 33 more
Caused by: com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: Failed to execute aapt
    at com.android.build.gradle.internal.transforms.InstantRunDependenciesApkBuilder.transform(InstantRunDependenciesApkBuilder.java:152)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:221)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:217)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
    ... 48 more
Caused by: com.android.ide.common.process.ProcessException: Failed to execute aapt
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:809)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:797)
    at com.android.build.gradle.internal.transforms.InstantRunSplitApkBuilder.generateSplitApkResourcesAp(InstantRunSplitApkBuilder.java:375)
    at com.android.build.gradle.internal.transforms.InstantRunSplitApkBuilder.generateSplitApkResourcesAp(InstantRunSplitApkBuilder.java:323)
    at com.android.build.gradle.internal.transforms.InstantRunSplitApkBuilder.generateSplitApk(InstantRunSplitApkBuilder.java:211)
    at com.android.build.gradle.internal.transforms.InstantRunDependenciesApkBuilder.transform(InstantRunDependenciesApkBuilder.java:149)
    ... 51 more
Caused by: java.util.NoSuchElementException
    at com.google.common.collect.AbstractIndexedListIterator.next(AbstractIndexedListIterator.java:80)
    at com.google.common.collect.Iterators.getOnlyElement(Iterators.java:315)
    at com.google.common.collect.Iterables.getOnlyElement(Iterables.java:263)
    at com.android.builder.internal.aapt.v1.AaptV1.makePackageProcessBuilder(AaptV1.java:202)
    at com.android.builder.internal.aapt.AbstractProcessExecutionAapt.makeValidatedPackage(AbstractProcessExecutionAapt.java:67)
    at com.android.builder.internal.aapt.AbstractAapt.link(AbstractAapt.java:34)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:807)
    ... 56 more

Removing android.enableAapt2=false fixes this but then it hits the current bug...

i managed to solve this problem by change gradle version from 3.1.1 to 3.0.1

Any fix for this please?

@sirphemmiey, you can try the PR from @CFKevinRef. It worked for me

The best fix for me was to temporarily revert to gradle 2.3.3 as suggested by @akrumel

classpath 'com.android.tools.build:gradle:2.3.3'

+1, I have the same issue

+1, the same issue

Using the following configuration and everything works fine

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.3'

    defaultConfig {
        applicationId "in.example"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:27.1.1"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

project level build.gradle

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        classpath 'com.google.gms:google-services:3.2.1'
    }
}

In order to use gradle 4.4 you will need to modify your gradle.properties file to look like this

#Fri Mar 02 12:52:38 IST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

@judemanutd even the release build works?

Yes, has been replicated by another user as well, you can follow up here https://github.com/invertase/react-native-firebase/issues/995#issuecomment-383651829

The release build does work following @judemanutd setup, but silently ignores bundled assets 馃槥
See my comment https://github.com/invertase/react-native-firebase/issues/995#issuecomment-383849080

Using the workaround android.enableAapt2=false fixed the missing bundled assets in the final APK though.

When i add android.enableAapt2=false to android/gradle.properties, another error occurred:

error: Duplicate file.
Original is here. The version qualifier may be implied.

Still having the same issue.

Have gone through each possible solution individually and nothing works.

android.enableAapt2=false is not a fix for more complicated apps, as others have pointed out, it causes build failures on other dependencies. None of the other workarounds solve the problem, is there any timeline for a fix on this?

Versions:
react-native: 0.55.3
gradle: 3.1.0

Hi, coming late to the party I know. But I found a fix for the problem in my case that may work for others. As described in the React Native Images I had @2x and @3x suffixes on some .png files, e.g.:

ui/images/question.png
ui/images/[email protected]
ui/images/[email protected]

Turns out if I delete the plain .png file and leave the @2x.png and @3x.png files the problem goes away, and the images are sized correctly in my app. I also have plain .png files in my project and they work fine. So it would appear that are supposed to have either have one or the other, but not both. 馃槣

UPDATE 5/29/2018: OK, this stopped working for me. I also tried to rename the file [email protected] as mentioned below, but that didn't work either. In the end the only thing that worked consistently was the android.enableAapt2=false in the gradle.properties file.

I came upon same issue.

react 16.2.0
gradle 3.1.2
appcompat 27.0.2

Deleting images from node_modules was like a rabbit chase.
I tried @CFKevinRef proposed solution - switching to react.gradle suggested in #17967 and everything worked good, without the need to delete any images.

Hi @samehgerges, your method seems to work but I am getting a Error:Cannot add task ':app:bundleDebugJsAndAssets' as a task with that name already exists. error that is preventing final build.

Did you come across that problem, and if yes, how did you fix?

Let me know if you need more info

@iqbalshirol's answer worked for me but I will point out that you should add org.gradle.configureondemand=true in your ~properties.gradle~ gradle.properties file not build.gradle. I agree it's the best solution as of now

I am using @CFKevinRef solution as well and it works well. Hope that gets incorporated soon.

@react-native-bot I will have the same bug with version 0.55, as do other people in the thread. The tag is not appropriate.

I agree. This is still an issue

I hate @react-native-bot

0.55.3 the same

0.55.4 the same.

org.gradle.configureondemand=true works, but the react-native-vector-icons are not loading =//

Hi @steveamaza , Did you mean gradle.properties? Could you please share your properties.gradle?(or gradle.properties) Thank you

@TruePai yes, I mean gradle.properties. Apologies. However, it stopped working. The react.gradle file at https://github.com/facebook/react-native/pull/17967 is what eventually helped

Can anyone get #17967 working with react-navigation? I am getting Duplicate resources error about some drawables...

EDIT: My bad - I forgot to remove some files generated by previous scripts from drawables folder... If you stumble upon similar issue, make sure to go over your drawables folder...

@iqbalshirol
Note: Make sure gradle.properties does not include org.gradle.configureondemand=true as that will make release build skip bundling JS and assets into the APK.

org.gradle.configureondemand=true

worked for me, but you need to add it to grade.properties not build.gradle

If somebody is actually interested into renaming png to try out one of the possible workaround of this thread:

for f in *.png; do mv "$f" "${f/\.png/@1x.png}"; done

@iqbalshirol after that adjustments: https://github.com/facebook/react-native/issues/16906#issuecomment-365790350

Executing task ':react-native-config:processReleaseResources' (up-to-date check took 0.012 secs) due to:
  Output file /home/paneladm/projects/my-react-native-app/node_modules/react-native-config/android/build/generated/source/r/release/com has been removed.
  Output file /home/paneladm/projects/my-react-native-app/node_modules/react-native-config/android/build/generated/source/r/release/com/facebook/fbui has been removed.
  Output file /home/paneladm/projects/my-react-native-app/node_modules/react-native-config/android/build/generated/source/r/release/com/facebook/drawee/backends has been removed.
All input files are considered out-of-date for incremental task ':react-native-config:processReleaseResources'.
Starting process 'command '/home/paneladm/Android-sdk/build-tools/23.0.1/aapt''. Working directory: /home/paneladm/projects/my-react-native-app/node_modules/react-native-config/android Command: /home/paneladm/Android-sdk/build-tools/23.0.1/aapt package -f --no-crunch -I /home/paneladm/Android-sdk/platforms/android-23/android.jar -M /home/paneladm/projects/my-react-native-app/node_modules/react-native-config/android/build/intermediates/manifests/aapt/release/AndroidManifest.xml -S /home/paneladm/projects/my-react-native-app/node_modules/react-native-config/android/build/intermediates/res/merged/release -m -J /home/paneladm/projects/my-react-native-app/node_modules/react-native-config/android/build/generated/source/r/release --custom-package com.lugg.ReactNativeConfig --non-constant-id -0 apk --output-text-symbols /home/paneladm/projects/my-react-native-app/node_modules/react-native-config/android/build/intermediates/bundles/release --no-version-vectors
:react-native-config:processReleaseResources FAILED
:react-native-config:processReleaseResources (Thread[Daemon worker Thread 3,5,main]) completed. Took 0.023 secs.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-config:processReleaseResources'.
> com.android.ide.common.process.ProcessException: Failed to execute aapt

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.

BUILD FAILED

Total time: 2.478 secs
Stopped 0 compiler daemon(s).
Received result Failure[value=org.gradle.initialization.ReportedException: org.gradle.internal.exceptions.LocationAwareException: Execution failed for task ':react-native-config:processReleaseResources'.] from daemon DaemonInfo{pid=16452, address=[92dc3c4a-b654-48d2-ba9d-9340a238bb3e port:44114, addresses:[/0:0:0:0:0:0:0:1%lo, /127.0.0.1]], idle=true, lastBusy=1527447310867, context=DefaultDaemonContext[uid=718563ec-a930-43ea-afad-de04432fc821,javaHome=/usr/lib/jvm/jdk1.8.0_172,daemonRegistryDir=/home/paneladm/.gradle/daemon,pid=16452,idleTimeout=10800000,daemonOpts=-XX:MaxPermSize=256m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=UTF-8,-Duser.country=US,-Duser.language=en,-Duser.variant]} (build should be done).
paneladm@debian:~/projects/my-react-native-app/android$ 

@judemanutd I changed to 27.0.3 and followed your steps but.. #19467

The app have a grey screen and the console output of Chrome Dev Tools from http://<local-IP>:8081/debugger-ui/ has a CORS error:

Failed to load http://localhost:8081/index.delta?platform=android&dev=true&minify=false: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://<local-IP>:8081' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
(index):186 Uncaught (in promise) TypeError: Failed to fetch

Got the same error after doing all what is recommended. So What's next? :(

I was on a react-native project for about a year and we had this problem since late 2017. We followed the steps here https://medium.com/@nhancv/react-native-build-release-duplicate-file-original-is-here-the-version-qualifier-may-be-implied-115e967c59e6. I would recommend having an automated script to deal with the issue. I'm not sure how long it will take until someone submits a real fix to the react-native community but the workaround from the link helped us out greatly.

@AugustoAleGon This worked for me

https://github.com/react-navigation/react-navigation/issues/1976#issuecomment-325019683

Likely not the best long term solution, but I needed to get a release out the door!

any update on this?

@FSPinho Also have the same issue, vector icons not showing but I also removed org.gradle.configureondemand=true and enabled aapt, assembleRelease now works but vector-icons don't show anymore, no update on this?

Any update on this issue?

Any update on this issue?

None of org.gradle.configureondemand=true or disabling aapt2 work arounds fixed my case. I end up putting all my image resources in Android project's drawable folder, and change my RN code to reference images from there.

We were hit with this bug as well. I found a work around without disabling things.

In my app/build.gradle file, I simply put this:

project.ext.react = [
    ...
    bundleInRelease: true,
    resourcesDirRelease   : "release/res"
]

Was able to successfully build in my build system. Thanks for all the help!

@steveamaza It works for me too. By the way, you should clean the android/app/build first after adding org.gradle.configureondemand=true in the gradle.properties.

Hey guys, I found a temporary solution for this, not sure is this a good idea, but it work for me. I also used the org.gradle.configureondemand=true and android.enableAapt2=false before, but it also cause me other issue. I saw there are few library have the png flat file issue, like react-navigation , react-native-calendars , react-native-datepicker , even I put my png file to the resources folder also have the issue, but I make it to jpeg solve the tinny issue. Now get into the point.

I using react-native-calendars and I found those png file in the folder and delete it all. Then, I rebuild to see which js file using it, then I comment the code mostly Image require, then you can decide you want to use react-native-vector-icons for replacement or just leave it alone if you not using it. Then flat file problem temporary solved, basically I no using any of the arrow for the png file, but I doing this is not a bad things.

Hope help others =)

Hello guys, any update about an official fix for this bug?

org.gradle.configureondemand=true( add it to grade.properties ) also worked for me, but first should clean project( delete apk/app-release.apk )

After adding:

android.enableAapt2=false

You also need to restart Gradle by launching in a terminal in the android directory:

./gradlew --stop

@davidperrenoud Unfortunately, this didn't work for me. I've also tried the solution from this thread as well, but that didn't work either. I hope this issue won't lose traction.

This is still happening in 0.55.4.

None of the solutions on this thread worked for me, still can't build my release.

See this PR for the official fix coming soon(tm).

https://github.com/facebook/react-native/pull/17967

@jameslporter i tried that code on myreact.gradle file but i got duplicated images error on
(all images inside this folder) android/app/src/main/res/drawable-mdpi/ and
(all images inside this folder) /android/app/build/generated/res/react/release/drawable-mdpi/

so after uninstalling code push i was able to build APK with this solution #17967
Thanks.

Any solution?

Eu resolvi o problema!
node_modules_reactnavigation_src_views_assets_backicon.png
N茫o sei qual procedimento exatamente resolveu...

Primeiro renomeei todas as imagens retirando
todos os '@'em node/modules/reactnavigation/src/views/assets/

depois em react native//node_modules/react-navigation/src/views/Header

Em Header.js comentei a linha 478
//source={require('../assets/back-icon-mask.png')}

Em HeaderBackButton.js linha 13
const defaultBackImage = null;//require('../assets/back-icon.png');

Em ModularHeaderBackButton.js linha 6
const defaultBackImage = null;//require('../assets/back-icon.png');

Aparentemente o pacote react-navigation era o culpado pelo bug.

@sashaba yeah you probably had to clean your build directory first.

@Dhrupal look at the PR I referenced a few comments up. Fix is coming there, hopefully.

I had the same issue as in https://github.com/react-navigation/react-navigation/issues/3315
I solved it this way:
Firstly bundled JS project with this 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
and then generated signed APK on Android Studio, which fortunately worked for me
(I did not changed anything in gradle.properties

I'm not yet familiar with gradle so didn't want to mess with my build config and screw things up even more. Here's the terribly-hacky-but-reliable workaround I came up with - just delete the duplicate files as soon as they're created.

Run in another terminal:
watch -n 0.1 "yes | rm <ABSOLUTE_PATH>/android/app/build/intermediates/res/merged/release/drawable-mdpi/*"

And then start your build as you normally would.

Looking forward to seeing a release soon with the fix!

@hramos Which commit fixed it?

@samehgerges solution work for me with some fixes.
in app/build.gradle file replace

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

with

project.ext.react = [
    entryFile: "index.js",
    bundleInRelease        : true,
    resourcesDirRelease   : "src/release/res"
]
apply plugin: 'com.android.application'

This last workaround from @iswanj doesn't work with RN 0.57.0-rc.0

org.gradle.configureondemand=true work for me. i just rm -rf build && ./gradlew assembleRelease and it worked. thank you for all the people in the thread who helped with this issue. you guys rock.

RN 0.55.2
combination of
org.gradle.configureondemand=true
android.enableAapt2=false
worked for me

This should be fixed in 0.57 (see da6a5e0439c168147271ef66ad5ebbeebd6fce3b).

Until this got fixed, there is another workaround similar to solution proposed by @CFKevinRef. This solution also allows you to keep using AAPT2. Workaround consists of three steps

  • change default bundling output folder to be in src/ directory instead of build folder. You can do this by changing react properties at the top of your build.gradle (app build gradle)
ext.react = [
        bundleInRelease        : true,
        resourcesDirRelease   : "src/release/res"
]
apply from: "../react.gradle" /*Check file for more information*/
apply plugin: 'com.android.application'

please note that properties names are dynamic and depends on your target names, bundleIn, resourcesDir

  • Add generated files to git ignore, to keep your native resources folder clean
    android/app/src/*/res/*/reactnative_*.png
    android/app/src/*/res/*/node_modules_*.png
  • Reverse dependency between this react gradle task (bundling) and merging assets and resources.
    This is the hardest part, you need to change this file {project_root_dir}/node_modules/react-native/react.gradle, In my case I copied this file to my project and keep updating it with each react release. The change is quite simple
    replace
currentBundleTask.dependsOn("merge${targetName}Resources")
currentBundleTask.dependsOn("merge${targetName}Assets")

with

runBefore("merge${targetName}Resources", currentBundleTask)
runBefore("merge${targetName}Assets", currentBundleTask)

THIS WORKED FOR ME, THANK YOU!

This works for me on latest RN

I did have to remove android.enableAapt2=false from android/gradle.properties first because I had added it there before as the temp fix.

Thanks RN team

Is this fix also added to 0.56.0 RN version?

The reason it didn't work for me was because my gradle.properties file was missing ...

React Native 0.48 I found solution for my issues, updating
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10-all.zip
classpath 'com.android.tools.build:gradle:3.2.0'
and
https://stackoverflow.com/questions/44446523/unable-to-load-script-from-assets-index-android-bundle-on-windows/44476757#44476757

android.enableAapt2=false initially did not work for me until i did sudo gem install cocoapods on OSX.
On ubuntu, sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386 should make it work.

@marcosbenevides

Could you please clarify what is your version of React and React Native? And maybe you will provide your full react.gradle file. Thanks in advance!

This should be fixed in 0.57 (see da6a5e0).

I have "react-native": "^0.57.1", this issue still occurs.

@khemrajsharma you need to bump to the version 0.57.3.

@SandroMachado [email protected] expects peer dependency [email protected] which is still buggy

The issue seemed to disappeared after I stepped back to this and deleted my build folder and rebuilt.

    "react": "16.5.0",
    "react-native": "0.57.1"

I am using the 0.57.3 and didn't find any significant bug.

@rumax
Do yo use react-native-toast-native library in your project? It was a reason of the issue with uncompiled PNG for me. I have a react native 0.57.0

I had the same issue. But did not fix with - android.enableAapt2=false, as this has issues with other drawable resources in the project.

Fixed it with adding org.gradle.configureondemand=true in build.gradle, which shall disable the 'bundleReleaseJsAndAssets' task to run, which is the best solution and works in any condition. Hope this helps.

@iqbalshirol thanks for your suggestion. My project works again but what does org.gradle.configureondemanddo? Doesn't configure the native libraries in node_modules? Is it necessary?

This is my list of native libraries at the moment:

"react-native-animatable": "^1.3.0",
    "react-native-config": "^0.11.5",
    "react-native-countdown-component": "^1.7.3",
    "react-native-dropdownalert": "^3.5.0",
    "react-native-firebase": "^5.0.0",
    "react-native-image-pan-zoom": "^2.1.9",
    "react-native-modal-overlay": "^1.2.3",
    "react-native-modalbox": "^1.6.0",
    "react-native-qrcode-svg": "^5.1.0",
    "react-native-splash-screen": "3.0.6",
    "react-native-svg": "^6.5.2",
    "react-native-table-component": "^1.1.8",
    "react-native-version-number": "^0.3.4",
    "react-native-version-up": "^1.0.9",
    "react-navigation": "^2.5.5",

Thank you!

android.enableAapt2=false

android.enableAapt2=false not working for me.is there any other solution?

android/app/build/intermediates/res/merged/debug/drawable-hdpi/node_modules_reactnavigationstack_dist_v iews_assets_backicon.png: error: uncompiled PNG file passed as argument. Must be compiled first into .flat file.. error: failed parsing overlays.

this is the issue for me
Adding android.enableAapt2=false to android/gradle.properties
is work for me

It is fixed in >=0.57.3.

Was this page helpful?
0 / 5 - 0 ratings