Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all 28482 articles
Browse latest View live

How to rename / move a folder in react native fs?

$
0
0

I am having trouble renaming and moving folders cause react native fs has only moveFile option that performs on files only and not folders.Doing it recursive is also messy and it is hard to execute lines after performing rename or move option due to synchronous execution.I have attached the code for move below with the bug.Kindly help me figure this out.

moveAll = (path, outputPath) => new Promise((resolve, reject) => {// is a folderif (path.split(".").length == 1) {  // CHeck if folder already exists  RNFS.exists(outputPath)    .then((exists) => {      if (exists) {        // Delete the folder if exists        RNFS.unlink(outputPath)          .then(() => {          })          // `unlink` will throw an error, if the item to unlink does not exist          .catch((err) => {            console.log(err.message);          });      }      // MAKE FRESH FOLDER      RNFS.mkdir(outputPath);      resolve(RNFS.readDir(path)        .then((result) => {          result.map(            (item) =>              new Promise((resolve, reject) => {                resolve(this.moveAll(item.path, outputPath +"/" + item.name));              })          )        })        .catch((e) => {          console.log("ERROR", e)        })      )    })    .catch((e) => {      console.log(e)    })} else {  RNFS.moveFile(path, outputPath)    .then(() => {    })    .catch((e) => {      console.log(e)    })}})

Thanks in advance :)


Build Failing for React Native iOS, "Multiple commands produce" Error

$
0
0

We were working on a react native project. One of my team members added some native modules on Linux and linked android. By then I am trying to link things in iOS but the build is always failing with this kind of error trace. The Android project is building normally.

I deleted xyz.xcworkspace and Podfile.lock then tried pod install.
Also, I tried to delete my node_modules and then yarn install followed by yarn link.

react-native-cli: 2.0.1  react-native: 0.61.4  yarn 1.19.1Pod 1.8.4XCode Version 11.2.1 (11B500)macOS Catalina 10.15.1 (19B88)

xyz warning

duplicate output file '/Users/user/Library/Developer/Xcode/DerivedData/xyz-hhesslamjsqmbobykhskliclusph/Build/Products/Debug-iphonesimulator/xyz.app/AntDesign.ttf' on task: PhaseScriptExecution [CP] Copy Pods Resources /Users/faisal/Library/Developer/Xcode/DerivedData/xyz-hhesslamjsqmbobykhskliclusph/Build/Intermediates.noindex/xyz.build/Debug-iphonesimulator/xyz.build/Script-47F818C57EEC47EA3303EA1B.sh

xyz workspace errors

Multiple commands produce '/Users/user/Library/Developer/Xcode/DerivedData/xyz-hhesslamjsqmbobykhskliclusph/Build/Products/Debug-iphonesimulator/xyz.app/Zocial.ttf':1) Target 'xyz' (project 'xyz') has copy command from '/Users/user/Desktop/xyz/native/node_modules/react-native-vector-icons/Fonts/Zocial.ttf' to '/Users/user/Library/Developer/Xcode/DerivedData/xyz-hhesslamjsqmbobykhskliclusph/Build/Products/Debug-iphonesimulator/xyz.app/Zocial.ttf'2) That command depends on command in Target 'xyz' (project 'xyz'): script phase “[CP] Copy Pods Resources”

There are multiple errors and warnings like this but have same format with different file names.

Change package name for Android in React Native

$
0
0

I used react-native init MyApp to initialise a new React Native app.This created among others an Android project with the package com.myapp.

What's the best way to change this package name, for example to: com.mycompany.myapp?

I tried changing it in AndroidManifest.xml but it created other errors, so I'm assuming it's not the way.

Any idea?

ReactNative Expo app wrongly listed details in Play Console

$
0
0

I've uploaded a React Native app built in via Expo. I've set permissions to none:

{"expo": {"android": {"permissions": []      ... other settings    }    ... other settings}

And I've set it to portrait mode only:

{"expo": {"orientation": "portrait",    ... other settings  }}

But when I upload the app-bundle to the PLayConsole it lists the app with 15 permissions:

android.permission.ACCESS_NETWORK_STATE android.permission.ACCESS_WIFI_STATE android.permission.FOREGROUND_SERVICE android.permission.INTERNET android.permission.MODIFY_AUDIO_SETTINGS android.permission.RECEIVE_BOOT_COMPLETED android.permission.REQUEST_INSTALL_PACKAGES android.permission.STORAGE android.permission.SYSTEM_ALERT_WINDOW android.permission.USE_BIOMETRIC android.permission.WAKE_LOCK com.google.android.c2dm.permission.RECEIVE com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE com.sja.firstaid.permission.C2D_MESSAGE host.exp.exponent.permission.C2D_MESSAGE

and both orientations under features:

2 features: android.hardware.screen.landscape, android.hardware.screen.portrait

I cannot identify a reason for either of these settings to be ignored.

react-native run-android is unrecognized

$
0
0

I've installed react-native-cli globally:

npm install -g react-native-cli

Then run:

react-native init AwesomeProjectcd AwesomeProject

I got the following structure:

-- AwesomeProject   ---- node_modules      ------ react-native    

When I run react-native run-android I get an error:
Command run-android unrecognized. Did you mean to run this inside a react-native project?

When I run react-native start I get the same.

react-native -v
prints:
react-native-cli: 0.2.0
react-native: n/a - not inside a React Native project directory

What I'm doing wrong?

Open app that is running on background! React native

$
0
0

Hi i am developing an application and in this moment i need open the app if the same is running on background, i am thinking in open i when specific push notification arrive to the phone.

I don't know is this is posible

I am developing the app using react native

Thanks

dlopen failed: /lib/arm/libjnisgfplib.so has invalid shdr offset/size: 311508/920

$
0
0

I am having following error of .so library on 32-bit android devices:

dlopen failed: "{some path}"==/lib/arm/libjnisgfplib.so has invalid shdr offset/size: 311508/920

Same code working fine in 64-bit device. I have jniLibs folder which has "armeabi-v7a", "x86", "arm64-v8a", "x86_64", "armeabi" folders and they all have libjnisgfplib.so file along with other .so files

In android/build.gradle I have:

    buildToolsVersion = "28.0.3"    minSdkVersion = 16    compileSdkVersion = 28    targetSdkVersion = 28    supportLibVersion = "28.0.0"

In app/build.gradle I have:

splits {    abi {        reset()        enable enableSeparateBuildPerCPUArchitecture        universalApk false  // If true, also generate a universal APK        include "armeabi-v7a", "x86", "arm64-v8a", "x86_64", "armeabi"    }}applicationVariants.all { variant ->    variant.outputs.each { output ->        def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4, "armeabi": 5]        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        }    }}

SQLite React-Native (react-native-sqlite-storage): no such table

$
0
0

I followed the react-native-sqlite-storage instructions on setting up the database but I'm encountering an error where it says there is SQL ERROR: {"no such table: users", code 5}

I've tried multiple styles where I have it in the "www" folder but to no avail.

import SQLite from 'react-native-sqlite-storage';...const database_name = "./users.db";const database_version = "1.0";const database_displayname = "Test";const database_size = 200000;...function loadAndQueryDB() {   //db = SQLite.openDatabase(database_name, database_version, database_displayname,      database_size, openCB, errorCB);   //db = SQLite.openDatabase({ name: './users.db', createFromLocation: 1,}, openCB, errorCB);   //db = SQLite.openDatabase({ name: 'users.db', createFromLocation: 1,}, openCB, errorCB);   //db = SQLite.openDatabase({ name: 'users', createFromLocation: 1,}, openCB, errorCB);    queryUsers(db);}function queryUsers(db) {    db.transaction((tx) => {      tx.executeSql('SELECT * FROM users', [], queryUsersSuccess, errorCB);    });  }

Execution failed for task ':app:compileDebugJavaWithJavac':

$
0
0

When I try $ react-native run-android on android emulator, I get this error:

:app:compileDebugJavaWithJavac/home/user/app/android/app/src/main/java/com/package/MainApplication.java:8: error: a type with the same simple name is already defined by the single-type-import of RNAWSCognitoPackageimport com.airlabsinc.RNAWSCognitoPackage;^1 errorIncremental compilation of 1 classes completed in 0.448 secs.:app:compileDebugJavaWithJavac FAILEDFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':app:compileDebugJavaWithJavac'.> Compilation failed; see the compiler error output for details.* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.BUILD FAILEDTotal time: 10.964 secsCould not install the app on the device, read the error above for details.Make sure you have an Android emulator running or a device connected and haveset up your Android development environment:https://facebook.github.io/react-native/docs/getting-started.html

Then I have 2 imports with the same name in my /home/user/app/android/app/src/main/java/com/package/MainApplication.javaMay this cause the issue?Is this the issue with RN?

package com.package;import android.app.Application;import com.facebook.react.ReactApplication;import com.amazonaws.RNAWSCognitoPackage; // 1import com.amazonaws.amplify.pushnotification.RNPushNotificationPackage;import com.airlabsinc.RNAWSCognitoPackage; // 2import com.horcrux.svg.SvgPackage;import com.toast.ToastPackage;import com.vdi.VDIPackage;import com.BV.LinearGradient.LinearGradientPackage;import com.facebook.react.ReactNativeHost;import com.facebook.react.ReactPackage;import com.facebook.react.shell.MainReactPackage;import com.facebook.soloader.SoLoader;import java.util.Arrays;import java.util.List;

My env:

**Environment**:  * OS: Linux 4.13  * Node: 8.9.4  * Yarn: Not Found  * npm: 5.6.0  * Watchman: Not Found  * Xcode: N/A  * Android Studio: Not Found**Packages**: (wanted => installed)  * react: 16.3.0-alpha.2 => 16.3.0-alpha.2  * react-native: 0.54.2 => 0.54.2

Detox - Could not initialize class DefaultKotlinSourceSetKt

$
0
0

I've followed the Detox guide for Android here to install on my react-native project - https://github.com/wix/Detox/blob/master/docs/Introduction.Android.md. But after running react-native run-android to build the app. I get the following error evaluating project :detox:

1: Task failed with an exception.-----------* Where:Build file 'C:\Users\brian\Documents\Projects\react-native-prototyping\node_modules\detox\android\detox\build.gradle' line: 2* What went wrong:A problem occurred evaluating project ':detox'.> Could not initialize class org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSetKt

I've looked in their issue tracker but didn't see a related issue. Looking at similar issues around Kotlin it seems it could be a conflict between my kotlin and gradle version. But I'm not sure how to determine the correct versions to use. I also did a ./gradlew clean in the android folder to no avail.

Question:

How can you resolve 'Could not initialize class ..sources.DefaultKotlinSourceSetKt' error?

Some details of my gradle and package setup are as follows:

"devDependencies": {"detox": "^16.5.0",    },

root build.gradle:

buildscript {    ext {        buildToolsVersion = "28.0.3"        minSdkVersion = 18        compileSdkVersion = 28        targetSdkVersion = 28        kotlinVersion = '1.3.0'    }    repositories {        google()        jcenter()    }    dependencies {        classpath("com.android.tools.build:gradle:3.5.2")        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}

app/build.gradle:

android {    compileSdkVersion rootProject.ext.compileSdkVersion    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    defaultConfig {        applicationId "com.testapp"        minSdkVersion rootProject.ext.minSdkVersion        compileSdkVersion rootProject.ext.compileSdkVersion        targetSdkVersion rootProject.ext.targetSdkVersion        // detox automated tests config        // This will later be used to control the test apk build type        testBuildType System.getProperty('testBuildType', 'debug')          testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'    }    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(System.getenv("KEYSTORE") ?: "keystore.jks")            storePassword System.getenv("KEYSTORE_PASSWORD")            keyAlias System.getenv("KEY_ALIAS")            keyPassword System.getenv("KEY_PASSWORD")        }    }    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"            // Detox-specific additions to pro-guard            proguardFile "${rootProject.projectDir}/../node_modules/detox/android/detox/proguard-rules-app.pro"        }    }    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"    }dependencies {    implementation fileTree(dir: "libs", include: ["*.jar"])    //noinspection GradleDynamicVersion    implementation "com.facebook.react:react-native:+"  // From node_modules    if (enableHermes) {        def hermesPath = "../../node_modules/hermes-engine/android/";        debugImplementation files(hermesPath +"hermes-debug.aar")        releaseImplementation files(hermesPath +"hermes-release.aar")    } else {        implementation jscFlavor    }    androidTestImplementation(project(path: ":detox"))}

Linking React Native (or any other framework) with Unity

$
0
0

So, I'm developing a mobile application in Unity and was wondering if it is possible to use it alongside React Native or any other framework in order to use UI elements for both iOS and Android with ease.

  • What I mean here is to develop the entire UI within the framework and when I click a button, it opens the Unity application.

If the above question is possible, I would like to go even further and ask if I can "mix" the unity app with the UI from the framework and make them switch information

  • Input form is inserted with the framework, the user types somethingand then unity gets that input and does something with it

Anxiously waiting for an answer. Thanks!!

React-native 0.61.2 with hermes disassembling index.android.bundle

$
0
0

I created a release build of my app with react-native 0.61.2 and enabled Hermes. In my Crashlytics I receive information about crashes along with stacktraces. Perviously I used to apply apktool to extract index.android.bundle from my apk, and it contained js code where I was able to find the issue by stacktrace.

But now using Hermes index.android.bundle seems to contain bytecode rather than js and I wasted a day trying to disassemble it. The last thing I tried was hbcdump tool mentioned in https://github.com/facebook/hermes/blob/master/doc/BuildingAndRunning.md, but all I get is "Error: fail to deserializing bytecode: Wrong bytecode version. Expected 73 but got 62"

What should I do to disassemble index.android.bundle created with Hermes? Any help is highly appreciated!

How do I do cross-origin requests from a WebView rendering local HTML?

$
0
0

I'm rendering a local static HTML file in a WebView that needs to do cross-origin requests to a server I control. Currently those requests are failing because the "Origin" header is being set as null by the WebView (probably because it's a local file). I've considered running a local HTTP server in the app and pointing the WebView to that, but then the "Origin" header would be set as http://localhost. I'm reluctant to add localhost to my CORS whitelist server-side, as I'm not sure what the security implications of that would be.

What would be the best approach to solving this problem?

How to pass an object back from a React Native Android module to Javascript

$
0
0

React Native's Native Module documentation for Android says that ReadableMap directly maps to a Javascript object. I assume this means that when I pass an object from Javascript to a native module, it is available as a ReadableMap.

How do I do the reverse, which is to create a dictionary (mapping string to string) in a native module and return it to Javascript via a callback?

React Native - How to Map Readable Array from React Native to Native Module in Android)?

$
0
0

I have a code in react native. I use it to pass array to native module, and I want to handle it on native module,

Example of ReadableArray:

{"AuditScheduleDetailID":5525,"AuditAnswerId":33,"LocalFindingID":1,"LocalMediaID":1,"ExtFiles":"jpg"}

I want to get each value of key inside - how can I do that?

I've tried this article but I dont really understand it.

I just hardcoded it for now like this :

@ReactMethodpublic void insert(ReadableArray name, String file) {    DatabaseHandler db = new DatabaseHandler(getReactApplicationContext());    String a = "path to file";    for(int i=0 ; i<name.size(); i++){    //expected result    int audit  = 5525 //from AuditScheduleDetailID value    int answer = 33 // from AuditAnswerId value    int finding = 1 // from LocalFindingID value    int media = 1 // from LocalMediaID value    String exten = "jpg" // from ExtFiles value    db.addContact(new Contact(audit, answer, finding, media, exten));    }}

Is there a way to get each value from readablearray key?


"SDK location not found" android error with React Native

$
0
0

I've been reading a lot, nothing is working, already tried:

  • write skd.dir = /home/fxn/Android/Sdk in the local.properties file
  • move that file to the project's root
  • set the ANDROID_SDK_ROOT environment variable

I just want to build a simple testing React Native app in apk file, I was following the instructions of the React docs and everything was fine, until I got this issue.

Here is the entire error log

FAILURE: Build failed with an exception.* Where:Build file '/home/fxn/node/reactNative/Test/node_modules/react-native- reanimated/android/build.gradle' line: 89* What went wrong:A problem occurred configuring project ':react-native-reanimated'.> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at '/home/fxn/node/reactNative/Test/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.orgBUILD FAILED in 3s

Appstate keep on getting change in React native in Android

$
0
0

I am working on React native project and there I am taking location permissions. Also I have to track location permissions always like if user has given permission access after install the application and then after sometime user goes to the app settings in device settings and disable/revoked the permissions. Again once app comes from background to foreground, I have to check permission based on that, Needs to show the messages.

So that, I am using Appstate. But, In Android strangely, After installed the application, If user denied the permission with "Dont show again" checkbox, Then Appstate getting keep on changing with background and active always. It is keep on loop.

componentDidMount = async () => {    AppState.addEventListener('change', this.handleAppStateChange);  };  componentWillUnmount() {    AppState.removeEventListener('change', this.handleAppStateChange);    Geolocation.clearWatch(this.watchID);  }  handleAppStateChange = async nextAppState => {    const {appState} = this.state;    console.log('nextAppState -->', nextAppState);    console.log('appState -->', appState);    if (appState === 'active') {      // do this      this.showLoader();      await this.requestAndroidLocationPermission();    } else if (appState === 'background') {      // do that    } else if (appState === 'inactive') {      // do that other thing    }    this.setState({appState: nextAppState});  };requestAndroidLocationPermission = async () => {    try {      const granted = await PermissionsAndroid.request(        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,        {},      );      if (granted === PermissionsAndroid.RESULTS.GRANTED) {        this.getLatitudeLongitude();      } else if (granted === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {        this.hideLoader();        this.setState({          errorMessage: 'Location permission is denied',          isLoading: false,        });      } else {        this.hideLoader();        this.requestAndroidLocationPermission();      }    } catch (err) {      console.warn(err);    }  };

It is keep on printing (loop) after denied permission with Don't show again

appState --> activenextAppState --> backgroundappState --> activenextAppState --> backgroundappState --> activenextAppState --> backgroundappState --> active

It goes on and never stop.

How to handle this? Any suggestions?

Getting Exceptions as Crash events

$
0
0

I am using react-native-firebase library for crash logs, I am getting crashes in the firebase console but I am getting some exceptions in crash events at firebase which should be log as non-fatal errors.

Infinite log in react native webview

$
0
0

I have a problem with my webview on react-native. The page I'm loading has a button to log in with google account.

When I don't define userAgent I get a 403 disallowed user agent error. If I define userAgent and click on the button. I connect with my google account and then I have an infinite loading screen. Do you have a solution for resolve my problem ? Thank you !

<WebView   source={{uri: "http://example.fr"}} (It s just for example)  userAgent="Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"  ref={this.WEBVIEW_REF}  onNavigationStateChange={this.onNavigationStateChange.bind(this)}/>

Loading Screen

Adb command similar to reverse?

$
0
0

I used to run adb reverse tcp:8081 tcp:8081 to connect/reconnect my devices to react native development server. but it's not supported on android 5. since adb reverse not supported on android <5x. i need it to do test app in old android versionalso i cant connect the device to react native server via wi-fi because it is an emulator

is there any similar command to do this?

Viewing all 28482 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>