Categories
Android React-Native

How I Run React Native App in Android?

Today we will try to create a blank react native project and run it on Android Device. We are not using the Expo app and trying to directly run on the android device. Thus, we do not require to install the expo app on Android Device. We will try to compile the React Native app with Android Build tools with Java and Gradle build. So, we need to install the few packages on our windows machine. Here is official React Native Guide to run app on devices.

First of all we need to have latest Node.js package installed on our machines. Also, the Node package manager (npm,yarn, pnpm etc). Once we have our node js installed on our machines we can navigate to our command prompt to create our react native project. You can follow the instructions provided on the official React Native GitHub repository. Here is how you can do this.

Goto the command prompt and hit the following command into your directory of project workspace.

npx create-react-native-appCode language: Bash (bash)
Create React Native App
Create React Native App

Running on Android Device

Connect your android phone to computer and don’t forget to allow the usb debugging for that computer. You need to enable the developer mode in your android device and have to enable the USB debugging in the developer options in the settings menu in your Android phone. You can also connect an emulator from the android studio. Once you connect the phone to your laptop it will prompt you to allow the computer for usb debugging on your phone. Allow the device and optionally you can also check to always allow checkbox from that dialogue box.

Once done you can simply Goto the command prompt and hit command

>>cd test2
>>npm run androidCode language: Bash (bash)

Error: JAVA_HOME is not set

While building your react-native app for android device your may see the error something like this.

JAVA_HOME is not set and no 'java' command could be found in your PATH. 
Please set the JAVA_HOME variable in your environment to match the 
location of your Java installation.Code language: JavaScript (javascript)

This error is simply because you don’t have Java Installed on your machine or you do not created the “JAVA_HOME” variable in your environment variable settings. Simply create a new variable in your environment variable settings for this and name it JAVA_HOME. If you do not have java installed on your machine, you may need to download and install it.

Error: Gradle not installed

Once you have JAVA installed and put the JAVA_HOME variable in your local machine, now you can again hit the npm run android command. When you try to run it on android you may end up in this error screen.


BUILD FAILED in 1m 27s
Error: E:\react-projects\my-react-app\android\gradlew.bat exited with non-zero code: 1
Error: E:\react-projects\my-react-app\android\gradlew.bat exited with non-zero code: 1
    at ChildProcess.completionListener (E:\react-projects\my-react-app\node_modules\@expo\spawn-async\build\spawnAsync.js:52:23)
    at Object.onceWrapper (node:events:629:26)
    at ChildProcess.emit (node:events:514:28)
    at cp.emit (E:\react-projects\my-react-app\node_modules\cross-spawn\lib\enoent.js:34:29)
    at maybeClose (node:internal/child_process:1105:16)
    at ChildProcess._handle.onexit (node:internal/child_process:305:5)
    ...
    at Object.spawnAsync [as default] (E:\react-projects\my-react-app\node_modules\@expo\spawn-async\build\spawnAsync.js:17:21)
    at spawnGradleAsync (E:\react-projects\my-react-app\node_modules\@expo\cli\build\src\start\platforms\android\gradle.js:72:46)
    at Object.assembleAsync (E:\react-projects\my-react-app\node_modules\@expo\cli\build\src\start\platforms\android\gradle.js:52:18)
    at runAndroidAsync (E:\react-projects\my-react-app\node_modules\@expo\cli\build\src\run\android\runAndroidAsync.js:36:24)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Code language: Bash (bash)

This error is simply because you do not have gradle installed on your machine. To resolve this error simply download and install the gradle latest version. If you do not know how to do it and you have choco installed on your machine, you can simply type this command in your Windows Power Shell.

choco install gradle

Once done, make sure to check if it is installed properly and globally by typing the version query command for the gradle like this

gradle -v

If this command returns the version number this means the gradle is now installed and accessible via command prompt, but if not, you may end up some installation error make sure if you are running your command prompt as an Administrator or not. If not, rerun your Windows Power Shell as an Administrator.

gradle not installed. An error occurred during installation:
 Unable to obtain lock file access on 'C:\ProgramData\chocolatey\lib\63b8df6024465284aa96552779f0f0464e19793f' for operations on 'C:\ProgramData\chocolatey\lib\gradle'. This may mean that a different user or administrator is holding this lock and that this process does not have permission to access it. If no other process is currently performing an operation on this file it may mean that an earlier NuGet process crashed and left an inaccessible lock file, in this case removing the file 'C:\ProgramData\chocolatey\lib\63b8df6024465284aa96552779f0f0464e19793f' will allow NuGet to continue.
gradle package files install failed with exit code 1. Performing other installation steps.
The install of gradle was NOT successful.
gradle not installed. An error occurred during installation:
 Unable to obtain lock file access on 'C:\ProgramData\chocolatey\lib\63b8df6024465284aa96552779f0f0464e19793f' for operations on 'C:\ProgramData\chocolatey\lib\gradle'. This may mean that a different user or administrator is holding this lock and that this process does not have permission to access it. If no other process is currently performing an operation on this file it may mean that an earlier NuGet process crashed and left an inaccessible lock file, in this case removing the file 'C:\ProgramData\chocolatey\lib\63b8df6024465284aa96552779f0f0464e19793f' will allow NuGet to continue.
This is try 1/3. Retrying after 300 milliseconds.
 Error converted to warning:
 Access to the path 'C:\ProgramData\chocolatey\lib-bad' is denied.
This is try 2/3. Retrying after 400 milliseconds.
 Error converted to warning:
 Access to the path 'C:\ProgramData\chocolatey\lib-bad' is denied.
Maximum tries of 3 reached. Throwing error.
Cannot create directory "C:\ProgramData\chocolatey\lib-bad". Error was:
System.UnauthorizedAccessException: Access to the path 'C:\ProgramData\chocolatey\lib-bad' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost)
   at System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean checkHost)
   at chocolatey.infrastructure.filesystem.DotNetFileSystem.<>c__DisplayClass63_0.<CreateDirectory>b__1()
   at chocolatey.infrastructure.tolerance.FaultTolerance.<>c__DisplayClass1_0.<Retry>b__0()
   at chocolatey.infrastructure.tolerance.FaultTolerance.Retry[T](Int32 numberOfTries, Func`1 function, Int32 waitDurationMilliseconds, Int32 increaseRetryByMilliseconds, Boolean isSilent)
   at chocolatey.infrastructure.tolerance.FaultTolerance.Retry(Int32 numberOfTries, Action action, Int32 waitDurationMilliseconds, Int32 increaseRetryByMilliseconds, Boolean isSilent)
   at chocolatey.infrastructure.filesystem.DotNetFileSystem.CreateDirectory(String directoryPath, Boolean isSilent)
   at chocolatey.infrastructure.filesystem.DotNetFileSystem.EnsureDirectoryExists(String directoryPath, Boolean ignoreError, Boolean isSilent)

Chocolatey installed 0/0 packages.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).
Access to the path 'C:\ProgramData\chocolatey\lib-bad' is denied.
Code language: JavaScript (javascript)

Now when you will run the Windows Power Shell as an Administrator and re run the choco install gradle It will be installed and this will be the final output.

PS C:\WINDOWS\system32> choco install gradle
Chocolatey v2.2.2
Installing the following packages:
gradle
By installing, you accept licenses for the packages.

gradle v8.4.0 [Approved]
gradle package files install completed. Performing other installation steps.
The package gradle wants to run 'chocolateyinstall.ps1'.
Note: If you don't run this script, the installation will fail.
Note: To confirm automatically next time, use '-y' or consider:
choco feature enable -n allowGlobalConfirmation
Do you want to run the script?([Y]es/[A]ll - yes to all/[N]o/[P]rint): a

Downloading gradle
  from 'https://services.gradle.org/distributions/gradle-8.4-all.zip'
Progress: 100% - Completed download of C:\Users\super\AppData\Local\Temp\chocolatey\gradle\8.4.0\gradle-8.4-all.zip (203.01 MB).
Download of gradle-8.4-all.zip (203.01 MB) completed.
Hashes match.
Extracting C:\Users\super\AppData\Local\Temp\chocolatey\gradle\8.4.0\gradle-8.4-all.zip to C:\ProgramData\chocolatey\lib\gradle\tools...
C:\ProgramData\chocolatey\lib\gradle\tools
Added C:\ProgramData\chocolatey\bin\gradle.exe shim pointed to '..\lib\gradle\tools\gradle-8.4\bin\gradle.bat'.
Environment Vars (like PATH) have changed. Close/reopen your shell to
 see the changes (or in powershell/cmd.exe just type `refreshenv`).
 The install of gradle was successful.
  Software installed to 'C:\ProgramData\chocolatey\lib\gradle\tools'

Chocolatey installed 1/1 packages.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).


PS C:\WINDOWS\system32> gradle -v

Welcome to Gradle 8.4!

Here are the highlights of this release:
 - Compiling and testing with Java 21
 - Faster Java compilation on Windows
 - Role focused dependency configurations creation

For more details see https://docs.gradle.org/8.4/release-notes.html


------------------------------------------------------------
Gradle 8.4
------------------------------------------------------------

Build time:   2023-10-04 20:52:13 UTC
Revision:     e9251e572c9bd1d01e503a0dfdf43aedaeecdc3f

Kotlin:       1.9.10
Groovy:       3.0.17
Ant:          Apache Ant(TM) version 1.10.13 compiled on January 4 2023
JVM:          21.0.1 (Oracle Corporation 21.0.1+12-LTS-29)
OS:           Windows 10 10.0 amd64
Code language: Bash (bash)

Error: The supplied javaHome seems to be invalid

Another possible error you may find would be incompatibility of the Gradle with your installed JDK version. Make sure to use a compatible version.

If you still got error something like below

The supplied javaHome seems to be invalid. 
I cannot find the java executable. 
Tried location: C:\Program Files\Java\jdk-21\bin\java.exeCode language: CSS (css)

This error is simply due to the invalid JAVA_HOME variable. If you tried to uninstall and reinstall the JDK then you may end up with this error. The only way to solve this is to use a valid javaHome variable. Goto you environment variables and change your JavaHome variable settings. Or you simply have duplicate jdk folders in your Java Home directory which was my case. Just `delete the old JDK 21 directory` and you are good to go.

Error: Could not Determine the Dependencies

Now that you resolved your different JAVA_HOME path error, you may end up a new error regarding the dependencies like this

Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Could not determine the dependencies of null.
   > SDK location not found. Define a valid SDK location with an ANDROID_HOME environment variable or by setting the sdk.dir path in your project's local properties file at 'E:\react-projects\test2\android\local.properties'.

* 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 4m 46sCode language: PHP (php)

According to this stackoverflow.com question, this is because we did not mention our Android SDK Path. To solve this, we have to mention our android SDK path. We can install the Android SDK or if we already installed the Android Studio, we can re-use the path of Android Studio create for the Android SDK manager. Here is how we can do that.

If you hit the command npx react-native doctor you will see a bunch of Red flags which you need to handle. Here is how it is looking in my case so far.

npx react-native doctor

As you can see our now red flags 🎌 are

  • We do not have adb available in our command prompt
  • Android SDK Required for building android install which is not found
  • ANDORID_HOME Environment variable that points to your Android SDK installation is not found

This Stackoverflow.com question help me to this solution. We are hitting 3 more errors to fix which we are going to remove in one go. We are going to install the Android SDK command line tools which will helps to reduce these errors. So for that we can open our android studio and go to our sdk manager and from there we can select the SDK commandline tools and install them.

Install lates Android SDK command line tools

You may need to create additional variable.

Add ANDROID_HOME variable to System Variables

After that you may only see the Android build versions difference like this and all other errors related to SDK path had been removed.

npx react-native doctor results.

In my case, I had version 33.0.1 and 34.0.0 installed but the React-Native so far only supports b33.0.0 version. So, I have to install the previous version in my Android SDK Manager as well. Simply open your SDK manager from android studio and installed the supported version. Once done again run the npx react-native doctor command and see if all the RED flags removed.

make sure to check “Show packages Details.”

Adding ADB to path

If your adb is not visible in the command prompt, make sure to add this to your Environment path location in system variable. In windows this path could be something like this.

C:\Users\[user]\AppData\Local\Android\Sdk\platform-toolsCode language: CSS (css)
Add android platform tools to your path variable

npm run android

Now if everything works is as expected and you try to run the npm run android it will be working like follows screenshot where everything looks green 🙂

and after that when build is successful.

React Native Successfully build

and the QR Code appears

Error: Failed to get properties for device

Now that everything build successfully, I am getting this final error which is related to the adb. Which is unable to get the device. Here is the complete logs of the error I encountered.

CommandError: Failed to get properties for device (097875436Y102724): Command failed: C:\Users\super\AppData\Local\Android\Sdk/platform-tools/adb -s 097875436Y102724 shell getprop ro.product.cpu.abilist
adb.exe: device offlineCode language: HTTP (http)

To inspect this I run the adb devices command on the terminal and figured that my device seems offline.

Device Offline

So I simply unplugged and re plugged my android device and now my device is active.

Android Device connected

Now I again try to run the npm run android and this is what was going on.

Android App is now running

Finally the Yurika moment that my app is running now on my android device. Here is the final command prompt screen shot which shows that everything goes green now.

Android Building Complete

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.