How to display current version number from build.gradle in app? - react-native

What is the best approach to display the current app version number in the app? Specifically, android\app\build.gradle has a "defaultConfig" object with "versionCode" and "versionName" properties. So let's say the current build.gradle configuration looks like this:
defaultConfig {
versionCode 9
versionName "0.1.9"
}
What would the code/implementation look like in order to pull this info from build.gradle and display it in a Text component in a parent component? I know that I could simply copy this information from the build.gradle configuration and paste it directly into the Text component. But the point of what I'm trying to do is to be 100% sure of the currently installed version of the app by propagating up that info into an app view directly from build.gradle.

Try installing the React Native Device Info Link component to get the build details as specified in the Gradle config.
Once installed you can use:
DeviceInfo.getVersion()
To output the version, and:
DeviceInfo.getBuildNumber()
To get the build number.

I use the package.json version as the app version. So we get the app version from package.json. when we change the package.json, the app version also changes.
const PackageInfo = require("../../../package.json");
localVersion : PackageInfo.version
but we have to first modify the native Android, to make it use the package.version as version name and code.
//in android project.build.gradle
def getNpmVersion() {
def inputFile = new File("../package.json")
def packageJson = new JsonSlurper().parseText(inputFile.text)
return packageJson["version"]
}
def getNpmVersionArray() {
// major [0], minor [1], patch [2]
def (major, minor, patch) = getNpmVersion().tokenize('.')
return [Integer.parseInt(major), Integer.parseInt(minor), Integer.parseInt(patch)] as int[]
}
subprojects {
ext {
def npmVersion = getNpmVersionArray()
versionMajor = npmVersion[0]
versionMinor = npmVersion[1]
versionPatch = npmVersion[2]
}
}
// then in app.gradle use it
defalultConfig{
...
versionCode versionMajor * 10000 + versionMinor * 100 + versionPatch
versionName "${versionMajor}.${versionMinor}.${versionPatch}"
...
}

Firstly, this might be a duplicated question. You can check this How to get a versionName in react-native app on Android?.
Secondly, if you're using CodePush to update your code, the above solution won't work because it only gets version of native built app.
If that's not what you need, please provide more details about your problem.

Also make sure to specify them in your build.gradle file instead of the AndroidManifest.xml:
defaultConfig {
versionCode 1
versionName "1.0"
}

Related

A failure occurred while executing com.android.build.gradle.internal.tasks.MergeNativeLibsTask$MergeNativeLibsTaskWorkAction

My react native project build fails somehow because of this error:
Execution failed for task ':app:mergeDebugNativeLibs'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.MergeNativeLibsTask$MergeNativeLibsTaskWorkAction
> 2 files found with path 'lib/arm64-v8a/libfbjni.so' from inputs:
- C:\Users\Antonio\.gradle\caches\transforms-3\7cca348744e25f57fc2d9f871aa73c9a\transformed\jetified-react-native-0.71.0-rc.0-debug\jni\arm64-v8a\libfbjni.so
- C:\Users\Antonio\.gradle\caches\transforms-3\08b0f5c7017bf081f79b63ea5b053dc0\transformed\jetified-fbjni-0.3.0\jni\arm64-v8a\libfbjni.so
If you are using jniLibs and CMake IMPORTED targets, see
https://developer.android.com/r/tools/jniLibs-vs-imported-targets
Anybody got a clue what could cause the build to fail? I haven't edited any build file and/or removed/installed/upgraded new packages thanks
For me this worked (after reading Tony's link), my version of react was 0.66.0
Changed this file android\app\build.gradle
implementation "com.facebook.react:react-native:+" // From node_modules
to
implementation "com.facebook.react:react-native:0.66.0!!" // From node_modules
Short answer:
in your android/app/build.gradle
change
implementation 'com.facebook.react:react-native:+'
to ---> (replace 0.67.2 with your current react native version)
implementation 'com.facebook.react:react-native:0.67.2!!'
Long answer:
This is happening because all the templates reference the React Native dependency by range, like implementation 'com.facebook.react:react-native:+'. Usually this dependency gets resolved from the local Maven repo in ./node_modules/react-native/android but since it has been published to Maven Central it's now grabbing the very latest RC.
You can resolve this problem by forcing the React Native dependency to the version you expect with something like this implementation 'com.facebook.react:react-native:0.67.2!!' in your app's Gradle file. The !! is shorthand for restricting Gradle from upgrading if your project or its transitive dependencies depend on a newer version.
work for me, if your react native application version >= 0.63 you can update the patch version which should fix your problem.
link: https://github.com/facebook/react-native/issues/35210#:~:text=We%20have%20prepared%20releases%20for%20all%20the%20main%20versions%20of%20react%2Dnative%20with%20an%20hotfix%3A
if not just go to android/build.gradle and then in the allprojects object add the following code with the current version of react native in package.json
configurations.all {
resolutionStrategy {
force 'com.facebook.react:react-native:CURRENT_VERSION_OF_REACT_NATIVE'
}
}
Here's a workaround to fix this problem if you are not using latest version of react-native.
https://github.com/facebook/react-native/issues/35210
Go to android folder -> build.gradle file -> inside allprojects object and add following code. Add react native version from node_modules -> react-native -> package.json // "version": "0.68.2".
configurations.all {
resolutionStrategy {
force 'com.facebook.react:react-native:0.68.2'
}
}
See fb/rn#35204
This is the Official recommended fix!
Found through this issue: https://github.com/facebook/react-native/issues/35210.
Copied from this PR here
For my RN 0.66.0 project I only had to add theses lines:
allprojects {
repositories {
exclusiveContent {
// Official recommended fix for Android build problem with React Native versions below 0.71
// https://github.com/facebook/react-native/issues/35210
// TODO: remove this exclusiveContent section when we upgrade to React Native 0.71 (or above)
// copied from https://github.com/Scottish-Tech-Army/Volunteer-app/pull/101/commits/40a30310ee46194efbaf1c07aef8a0df70231eeb
filter {
includeGroup "com.facebook.react"
}
forRepository {
maven {
url "$rootDir/../node_modules/react-native/android"
}
}
}
}
}
I had the same issue. There is a new patch for react-native now so update it in your package.json.
Mine is
"react-native": "^0.70.3"
and I changed it to
"react-native": "^0.70.5"
which worked for me
The answer lies here depending on the version of your react native. Patches are available for RN version 0.63 and up
https://github.com/facebook/react-native/issues/35210
Tips:
Don't just update react-native package, do an npm install
Clean gradle before running the app
Only add the code below IF your react native version is < 0.63
def REACT_NATIVE_VERSION = new File(['node', '--print',"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim())
allprojects {
configurations.all {
resolutionStrategy {
// Remove this override in 0.65+, as a proper fix is included in react-native itself.
force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION
}
}
}

React native custom buildType not using metro

I need to build the same app to different applicationIds so that I can publish it on the Play Store / App Store as private applications for some of the customers of my company.
I decided to use react-native-config, as it should allow me to change applicationId and some env variables easily.
I have created some .env.${variant} files, that is, in the following examples, .env.customer1.
I have set the needed buildTypes as follows:
...
buildTypes {
debug {
...
}
customer1 {
initWith debug
applicationIdSuffix "customer1"
}
}
I forced react.gradle not to bundle when building with these variants
project.ext.react [
bundleInCustomer1: false,
devDisabledInCustomer1: false
]
Then I use this command line to run on my physical device
copy .env.customer .env && react-native run-android --variant=customer1 --appIdSuffix 'customer1'
The result is that the app is built and launched on my device, but what I see is an old version of the app (probably the last one that I have built using assembleRelease, some weeks ago), metro getting launched but telling me this when I try to force a reload, otherwise telling me nothing
warn No apps connected. Sending "reload" ...
I tried without any success
gradlew clean
npm start --cache-reload
npm cache clean --forced
npm i
Building the app without any variant (thus using default debug) correctly works.
Thanks to this answer, I've succeeded in solving my issue.
Instead of using buildTypes now I'm using flavors.
So,
android {
...
flavorDimensions "standard"
defaultConfig {
applicationId "com.stackoverflow"
...
productFlavors {
customer1 {
applicationId "com.stackoverflow.customer1"
dimension "standard"
}
}
}
and launching via
react-native run-android --variant=customer1Debug --appIdSuffix 'customer1'

Error finding jetpack compose compiler Could not find androidx.compose:compose-compiler:1.0.0-alpha11

Im getting this error in an android project.
Could not find androidx.compose:compose-compiler:1.0.0-alpha11.
Searched in the following locations:
- https://maven.google.com/androidx/compose/compose-compiler/1.0.0-alpha11/compose-compiler-1.0.0-alpha11.pom
- https://jcenter.bintray.com/androidx/compose/compose-compiler/1.0.0-alpha11/compose-compiler-1.0.0-alpha11.pom
- https://repo.maven.apache.org/maven2/androidx/compose/compose-compiler/1.0.0-alpha11/compose-compiler-1.0.0-alpha11.pom
As you can see I have added the google repository based on the tutorials.
The build Gradle is configured like the following:
build.gradle.kts
dependencies {
val composeVersion = "1.0.0-alpha11"
//val composeVersion = "0.1.0-dev10"
implementation(project(":shared"))
//implementation ("androidx.compose.runtime:runtime:$composeVersion")
//implementation ("androidx.compose.compiler:compiler:$composeVersion")
implementation("com.google.android.material:material:1.2.1")
implementation("androidx.appcompat:appcompat:1.2.0")
implementation("androidx.constraintlayout:constraintlayout:2.0.4")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2")
implementation ("androidx.compose.ui:ui:$composeVersion")
// Tooling support (Previews, etc.)
//implementation ("androidx.compose.ui:ui-tooling:$composeVersion")
// Foundation (Border, Background, Box, Image, Scroll, shapes, animations, etc.)
implementation ("androidx.compose.foundation:foundation:$composeVersion")
// Material Design
implementation ("androidx.compose.material:material:$composeVersion")
// Material design icons
implementation ("androidx.compose.material:material-icons-core:$composeVersion")
implementation ("androidx.compose.material:material-icons-extended:$composeVersion")
// Integration with observables
implementation ("androidx.compose.runtime:runtime-livedata:$composeVersion")
implementation ("androidx.compose.runtime:runtime-rxjava2:$composeVersion")
//UI Tests
//androidTestImplementation 'androidx.compose.ui:ui-test-junit4:1.0.0-alpha10'
}
android {
compileSdkVersion(29)
defaultConfig {
applicationId = "com.myTempOrg.myTestApp.androidApp"
minSdkVersion(24)
targetSdkVersion(29)
versionCode = 1
versionName = "1.0"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerVersion = "1.4.21"
kotlinCompilerExtensionVersion = "1.0.0-alpha11"
}
kotlinOptions {
jvmTarget = "1.8"
useIR = true
}
I have also tried downgrading to alpha03 which seems to be found, but get another host of issues there with missing dependencies.
The kotlinCompilerVersion should be "1.4.21-2" with alpha 11.
Please note that alpha 12 is now out and you can upgrade using the following dependencies: link to alpha 12 dependencies
You also need to add this: link to further instructions for updating to alpha 12

How can I import OpenCV library to React-Native project

I tried to import OpenCV via native code but that not worked and I also tried react-native-opencv
library but that library doesn't contain all OpenCV methods.
How can I achieve to use OpenCV in my react-native project?
Thanks in advance.
I have been struggling with OpenCV in react-native for a week now and finally got it working. There is this very good article https://brainhub.eu/blog/opencv-react-native-image-processing/ together with this repo https://github.com/brainhubeu/react-native-opencv-tutorial which describes in details on how to do get it running. However I could not make the code from this repo working by following the steps described or following any other tutorial/video I could find. So in case if anyone is facing the same problem you can try this steps that made the app from the mentioned repo working with OpenCV v4.5 on my Android 10 device.
Open terminal and initialize new React-Native project
npx react-native init NAME_OF_YOUR_PROJECT
Navigate to path /main
cd NAME_OF_YOUR_PROJECT/android/app/src/main
Create new folder named jniLibs
mkdir jniLibs
Download and extract latest OpenCV for Android (tested with OpenCV 4.5) from https://opencv.org/releases/
Rename the "sdk" folder in the extracted folder (OpenCV-android-sdk) to "opencv"
Copy content from extracted folder (OpenCV-android-sdk/opencv/native/libs/) to newly created ./jniLibs
cp -r /PATH_TO_EXTRACTED_OPENCV_FOLDER/OpenCV-android-sdk/opencv/native/libs/ ./jniLibs
Open Android Studio and open Android folder of your projects dir
File -> Open -> select */NAME_OF_YOUR_PROJECT/android
Import OpenCV to your project
File -> New -> Import module -> select the folder you renamed to opencv
(IMPORTANT! Some tutorials say to select the "java" folder inside this folder - don't do that)
Under Gradle Scripts: open build.gradle(:opencv) and build.gradle(YOUR_PROJECT_NAME)
Change both to matching numbers - in my case:
minSdkVersion = 21
compileSdkVersion = 29
Add opencv to projects dependencies
File -> Project Structure -> Dependencies -> select app and press the "+" sign (located "underneath All dependencies") -> check the checkbox next to opencv -> press OK
In build.gradle(YOUR_APP_NAME) change version of gradle to 4.1.0
dependencies {
classpath("com.android.tools.build:gradle:4.1.0")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
Now open build.gradle(Project: NAME_OF_YOUR_PROJECT .app) and change java version in compile options and add packagin option with some pickfirst option. Also enable multidex option and if you wish to use react-native-camera add the missing dimension strategy. Should look something like this:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
pickFirst 'lib/x86/libc++_shared.so'
pickFirst 'lib/x86_64/libc++_shared.so'
pickFirst 'lib/armeabi-v7a/libc++_shared.so'
pickFirst 'lib/arm64-v8a/libc++_shared.so'
}
defaultConfig {
applicationId "com.stackoverflow" // !!! if copy-pasting change applicationId to yours
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
multiDexEnabled true
missingDimensionStrategy 'react-native-camera', 'general'
}
Open build.gradle(:opencv) and enable multidex option in default config. If you wish to use react-native-camera then also add missing dimension strategy. Should look something like this
defaultConfig {
minSdkVersion 21
targetSdkVersion 29
versionCode openCVersionCode
versionName openCVersionName
multiDexEnabled true
missingDimensionStrategy 'react-native-camera', 'general'
externalNativeBuild {
cmake {
arguments "-DANDROID_STL=c++_shared"
targets "opencv_jni_shared"
}
}
}
Also change the version of java in compile options (must be same as in build.gradle(:app). Should look something like this
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Add the following user permissions to your /PATH_TO_YOUR_PROJECT/android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Open gradle wrapper properties (/PATH_TO_YOUR_PROJECT/android/gradle/wrapper/gradle.properties) and change the version number of gradle
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip
Go to /YOUR_PROJECT_PATH/android/app/src/main/java/com/ and create reactlibrary folder then create two files inside that folder:
RNOpenCvLibraryModule.java
RNOpenCvLibraryPackage.java
Fill them with the same content as found on this GIT repo https://github.com/brainhubeu/react-native-opencv-tutorial/tree/master/android/app/src/main/java/com/reactlibrary
Open MainApplication.java and add this "packages.add(new RNOpenCvLibraryPackage());" to getPackage() method. Should look something like this:
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new RNOpenCvLibraryPackage()); // ADD THIS
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
Also add this to the onCreate() method:
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
if (!OpenCVLoader.initDebug()) { // ADD THIS
Log.d("OpenCv", "Error while init"); // AND THIS
} // DON'T FORGET THE "}"
}
Dont forget to add proper imports in the begining of your "MainApplication.java"
import org.opencv.android.OpenCVLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
Syncronize your project
File -> Syncronize Your Project with Gradle Files
Open the terminal and navigate to your project. Add this packages
cd /PATH_TO_YOUR_PROJECT/
npm i react-native-easy-toast --save
npm i react-native-svg --save
npm install --save react-native-camera#git+https://git#github.com/react-native-community/react-native-camera.git
(Make sure react-native-camera is installed from GIT repo otherwise you will encounter errors)
Create new folder nammed "src" in your PROJECT_PATH and copy the content of this repos ("https://github.com/brainhubeu/react-native-opencv-tutorial/tree/master/src") "src" folder to yours (/PATH_TO_YOUR_PROJECT/src/)
mkdir src
Copy the content of this repos "https://github.com/brainhubeu/react-native-opencv-tutorial/blob/master/App.js" App.js file and replace the content in your App.js file (located in YOUR_PROJECT_PATH)
Start react-native
npx react-native start
Run on Android device
npx react-native run-android
you can use this lib
react-native-opencv3
or you can exploit this project for using native Java and Objective-C bindings for OpenCV in react-native
If someone is still wondering here's the solution. It is quite some work to just set it up. You will have to write your OpenCV code in Java.
https://stackoverflow.com/a/63116300/10333905
sometimes the while trying to import opencv module, you will not proceed after selecting src directory. both next and finish option will be disabled. for this case.
create a folder "opencv" in the android folder and the copy all the files in the opencv sdk folder into this folder.
in setting.gradle add include ":opencv"
sync now.
goto project structure and add in dependency tab click on '+' icon on top app and select the module dependency and then opencv library.
Note:if the opencv is not present in the module dependency then you have copied the files wrongly. check whether the gralde file present in the files you copied

Android Studio 2.2 update cause DefaultManifestParser cannot be resolve

Recently I updated android studio to android studio 2.2 and using gradle 2.14.1. However, com.android.builder.core.DefaultManifestParser cannot be resolve after the update. Below are the codes that I am using. Any recommend workaround to solve this issue? Thanks
defaultConfig {
def manifestParser = new DefaultManifestParser(android.sourceSets.main.manifest.srcFile)
applicationId = manifestParser.getPackage()
versionName = manifestParser.getVersionName()
versionCode manifestParser.getVersionCode()
minSdkVersion manifestParser.getMinSdkVersion()
targetSdkVersion manifestParser.getTargetSdkVersion()
multiDexEnabled true
}
My defaultConfig setting is similar to yours and it's successfully built,
defaultConfig {
def manifestFile = (File) android.sourceSets.main.manifest.srcFile
def manifestParser = new DefaultManifestParser(manifestFile)
//noinspection GroovyAssignabilityCheck
applicationId = manifestParser.getPackage()
minSdkVersion 18
targetSdkVersion 23
//noinspection GroovyAssignabilityCheck
versionName = manifestParser.getVersionName()
//noinspection GroovyAssignabilityCheck
versionCode = manifestParser.getVersionCode()
}
so I guess probably the required *.jar hasn't been successfully downloaded during the IDE update. Could you double check whether the file builder-2.2.0.jar exists under the IDE folder(e.g., C:\Program Files\Android\android-studio_2.2\gradle\m2repository\com\android\tools\build\builder\2.2.0). If it does exist, can do a further checking to make sure the file DefaultManifestParser.class is really inside folder \com\android\builder\core by extracting builder-2.2.0.jar.
If the above mentioned file and class do exist, can also try using import com.android.builder.core.DefaultManifestParser, however, it's a bit weird that we have to use this.
Just think of there is another thing to check is the Gradle plugin class path, it should be like this
classpath 'com.android.tools.build:gradle:2.2.0'
I have same troubleļ¼Œand reback gradle version to 2.1.3 it is working
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
}