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

react-native-webview how to inject javascript?

$
0
0

On Android, I had been using expo-stripe-checkout for payments on an Expo managed app. Everything was working fine until I updated to the newest version of expo and react-native. Now, none of the callbacks, like onClose and onPaymentSuccess are working. It seems WebView was removed from react-native, so I'm importing directly from react-native-webview.

Instead of using expo-stripe-checkout, I created my own component, to try and work through what's happening, and it seems as if WebView's injectedJavaScript isn't running at all, and therefore window.postMessage or window.ReactNativeWebView.postMessage isn't working.

package.json:

{"name": "example","version": "0.0.6","private": true,"devDependencies": {"jest-expo": "^37.0.0","react-test-renderer": "16.0.0","schedule": "^0.4.0"  },"main": "./node_modules/expo/AppEntry.js","scripts": {"start": "expo start","eject": "expo eject","android": "expo start --android","ios": "expo start --ios","test": "node node_modules/jest/bin/jest.js --watch","prettier": "./node_modules/prettier/bin-prettier.js --single-quote --trailing-comma es5 --print-width 100 --write 'app/**/*.js' -l"  },"jest": {"preset": "jest-expo"  },"dependencies": {"@ptomasroos/react-native-multi-slider": "^1.0.0","@react-native-community/masked-view": "^0.1.10","@react-navigation/drawer": "^5.6.4","@react-navigation/native": "^5.2.3","@react-navigation/stack": "^5.2.18","axios": "^0.17.1","babel-plugin-transform-remove-console": "^6.9.4","emoji-utils": "^1.0.1","expo": "^37.0.0","expo-analytics": "^1.0.9","expo-apple-authentication": "^2.1.1","expo-av": "~8.1.0","expo-blur": "~8.1.0","expo-branch": "~2.1.0","expo-constants": "~9.0.0","expo-facebook": "~8.1.0","expo-font": "~8.1.0","expo-image-manipulator": "~8.1.0","expo-image-picker": "~8.1.0","expo-linear-gradient": "~8.1.0","expo-permissions": "~8.1.0","expo-stripe-checkout": "^1.0.1","immutability-helper": "^2.8.1","lottie-react-native": "~2.6.1","moment": "^2.22.1","prettier": "^1.12.1","react": "16.9.0","react-native": "0.61.4","react-native-animate-number": "^0.1.2","react-native-aws3": "0.0.9","react-native-branch": "4.2.1","react-native-calendars": "^1.20.0","react-native-circular-action-menu": "^0.5.0","react-native-circular-progress": "^1.0.1","react-native-datepicker": "^1.7.2","react-native-gesture-handler": "^1.6.1","react-native-gifted-chat": "0.13.0","react-native-google-places-autocomplete": "^1.4.0","react-native-invertible-scroll-view": "^1.1.1","react-native-keyboard-aware-scroll-view": "0.9.1","react-native-maps": "0.26.1","react-native-modal": "^11.5.3","react-native-modal-dropdown": "^0.6.2","react-native-reanimated": "^1.8.0","react-native-safe-area-context": "^0.7.3","react-native-screens": "^2.7.0","react-native-scroll-into-view": "^0.1.4","react-native-snap-carousel": "^3.7.2","react-native-status-bar-height": "^3.0.0-alpha.1","react-native-svg": "11.0.1","react-native-svg-icon": "^0.8.1","react-native-swipe-gestures": "^1.0.5","react-native-unimodules": "~0.8.1","react-native-webview": "^10.3.1","react-redux": "^5.0.7","react-timer-mixin": "^0.13.4","react-visibility-sensor": "^4.1.0","redux": "^4.0.0","redux-thunk": "^2.3.0","sentry-expo": "~2.0.0","socket.io-client": "^2.0.4"  }}

I've tried several different suggestions from around the web, but nothing has worked:

StripeCheckout.js

import React, { Component } from 'react';import { Platform, View, ViewPropTypes } from 'react-native';import { PropTypes } from 'prop-types';import { WebView } from 'react-native-webview'class StripeCheckout extends Component {  render() {    const {      publicKey,      amount,      allowRememberMe,      currency,      description,      imageUrl,      storeName,      prepopulatedEmail,      style,      onPaymentSuccess,      onClose    } = this.props;    const jsCode = `(function() {                    console.log('hello')                    var originalPostMessage = window.ReactNativeWebView.postMessage;                    var patchedPostMessage = function(message, targetOrigin, transfer) {                      originalPostMessage(message, targetOrigin, transfer);                    };                    patchedPostMessage.toString = function() {                      return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');                    };                    window.ReactNativeWebView.postMessage = patchedPostMessage;                  })();`;    const runFirst = `      console.log('firstRun')      window.isNativeApp = true;      true; // note: this is required, or you'll sometimes get silent failures    `;    return (<WebView        ref={(ref) => { this.webview = ref; }}        javaScriptEnabled={true}        injectedJavaScriptForMainFrameOnly={false}        scrollEnabled={false}        bounces={false}        messagingEnabled={true}        onMessage={(event) => console.log(event)}        onPaymentSuccess(event.nativeEvent.data)}        injectedJavaScriptBeforeContentLoaded={runFirst}        injectedJavaScript={jsCode}        source={{ html: `<script src="https://checkout.stripe.com/checkout.js"></script><script>            var handler = StripeCheckout.configure({              key: '${publicKey}',              image: '${imageUrl}',              locale: 'auto',              token: function(token) {                window.ReactNativeWebView.postMessage(token.id, token.id);              },            });            window.onload = function() {              console.log('onload')              handler.open({                image: '${imageUrl}',                name: '${storeName}',                description: '${description}',                amount: ${amount},                currency: '${currency}',                allowRememberMe: ${allowRememberMe},                email: '${prepopulatedEmail}',                closed: function() {                  window.ReactNativeWebView.postMessage("WINDOW_CLOSED", "*");                }              });            };</script>`}}        style={[{ flex: 1 }, style]}        scalesPageToFit={Platform.OS === 'android'}      />    );  }}StripeCheckout.propTypes = {  publicKey: PropTypes.string.isRequired,  amount: PropTypes.number.isRequired,  imageUrl: PropTypes.string.isRequired,  storeName: PropTypes.string.isRequired,  description: PropTypes.string.isRequired,  allowRememberMe: PropTypes.bool.isRequired,  onPaymentSuccess: PropTypes.func.isRequired,  onClose: PropTypes.func.isRequired,  currency: PropTypes.string,  prepopulatedEmail: PropTypes.string,  style: ViewPropTypes.object};StripeCheckout.defaultProps = {  prepopulatedEmail: '',  currency: 'USD',};export default StripeCheckout;

None of the console's are logging. The stripe integration pops up and returns a token successfully, but then nothing happens, and the component isn't receiving the token (i can see it's returning a token from the stripe logs).

Let me know if there's anything else I should post. Thanks!


React Native STOMP over websocket

$
0
0

I'm trying to build a React Native messaging app throught websocket and STOMP protocol (For the server side I'm using Spring Boot) but I get a really weird behaviour. My code is the following:

...import SockJS from 'sockjs-client'; // Note this lineimport Stomp from 'stompjs';function ChatScreen() {   // Variables declaration   useEffect(() => {    const socket = new SockJS('http://localhost:8080/chat');    const stompClient = Stomp.over(socket);    const headers = {Authorization: `Bearer ${jwt}`};    stompClient.connect(headers, () => {      stompClient.subscribe(        `/user/${user.username}/queue/messages`, console.log, headers,      );    });    return () => stompClient && stompClient.disconnect();  }, [jwt, user.username]);  ...}

When the above component is mounted I get:

Whoops! Lost connection to http://localhost:8080/chat

Then if I change the SockJS import line from import SockJS from 'sockjs-client'; to import SockJS from 'sockjs-client/dist/sockjs'; without reloading with double "r", but letting hot reloading do its job, I successfully obtain a connection to the websocket and everything works fine. Now, if I reload with double "r" and navigate to ChatScreen component again, I still get the message:

Whoops! Lost connection to http://localhost:8080/chat

Switching back to import SockJS from 'sockjs-client'; from import SockJS from 'sockjs-client/dist/sockjs'; I successfully obtain a new working connection but double "r" breaks it down again.

I tested the code on both an emulator (Android 9) and a physical device (Android 10). I've also tested react-stomp and the result is the same.

For a better understanding on what I mean this is a video that reports the behaviour:https://drive.google.com/open?id=1IVpiJjHsBGkhB38IWoPujI5eXPuBDbf1

I appreciate any help. Thank you

Boost audio volume more than 100% in react native

$
0
0

My app is music player and some of the mp3's have lower volume. I want to Boost audio volume more than 100% in react native.

I have to tried this plugin:

  • react-native-volume-control
  • react-native-system-setting
  • react-native-audio-manager
  • react-native-sound

Android-studio: Unable to locate adb

$
0
0

I read the answers "unable to locate adb" using Android Studio and Error:Unable to locate adb within SDK in Android Studio and it didn't solve my problem.

I use the 4.0 android-studio and Ubuntu 18.04

When I click on "launch this AVD in the emulator", I get an error message "Unable to locate adb".I did look in the Android/Sdk/platform-tools, I have an "adb" executable.

After the "unable to locate adb" error message, the AVD still launches. But, when I try to run my react native app on it, I get the error

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details. Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

I'm pretty sure the react-native part is fine, but that route to the emulator is not the same as before.

It was working before. Yesterday, out of the blue, when I launched my android-studio, it "restarted" (showing me the install wizard, etc), and it seems it messed up its configuration.

EDIT: [bad way] I created a new ubuntu user, re-install android studio + react-native. I still get the error message, still the AVD launches, but now React-native can install the app on it. So, now I can work with my new user, but I did not fix the problem.

EDIT2: [good way] @jpatmore fixed the android-studio part (see his answer).The react-native was still not working. There was probably some parameter of android-studio 3.6 still in the [my project]/android/[gradle or something]I cloned my repo in another folder, do another "npm install", "react-native link", and it was working.

how to run an existing project of react native

$
0
0

I wanted to download and run someone else's project in order to consider its functions. I ran into a number of problems ... that it does not deign to start, and I just don’t know what to do, help, please

https://github.com/sunlight3d/react_native_v0.49/tree/master/61-Realm%20React%20Native%235.Filter%20data%20and%20working%20with%20To-Many%20Relationships/code/tutorialProject

1) copied to the working folder tutorial project

2) opened VS code

3) went into the working folder and clicked open in cmd folder tutorial project

4) then I enter react-native run-androidand get fiasco

d:\JS\tutorialProject>react-native init tutorialProject internal/modules/cjs/loader.js:657 throw err; ^ Error: Cannot find module 'graceful-fs' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:655:15) at Function.Module._load (internal/modules/cjs/loader.js:580:25) at Module.require (internal/modules/cjs/loader.js:711:19) at require (internal/modules/cjs/helpers.js:14:16) at Object.<anonymous> (d:\JS\tutorialProject\node_modules\react-native\local-cli\cli.js:12:1) at Module._compile (internal/modules/cjs/loader.js:805:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:816:10) at Module.load (internal/modules/cjs/loader.js:672:32) at tryModuleLoad (internal/modules/cjs/loader.js:612:12) at Function.Module._load (internal/modules/cjs/loader.js:604:3)

I started googling and found something to do with some dependencies. Using react-native init MyProject

5) react-native init tutorialProject and getting the tighter right line

I try to start the server through npm and then it's funny ...6) npm-intall

d:\JS\tutorialProject>npm install npm WARN deprecated core-js@1.2.7: core-js@<2.6.5 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2. npm WARN deprecated connect@2.30.2: connect 2.x series is deprecated npm ERR! path d:\JS\tutorialProject\node_modules\.bin\react-native npm ERR! code EEXIST npm ERR! Refusing to delete d:\JS\tutorialProject\node_modules\.bin\react-native: is outside d:\JS\tutorialProject\node_modules\react-native and not a link npm ERR! File exists: d:\JS\tutorialProject\node_modules\.bin\react-native npm ERR! Move it away, and try again. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Nick\AppData\Roaming\npm-cache\_logs\2019-04-16T18_15_13_614Z-debug.log

and here I am absolutely don't know. How to run someone else's project?

(React native )After running signed apk undefiend code:-1 error displaying https domain

$
0
0

I am using the https domain.

I have created a react native app after i launched my signed apk after installing it showing . Error loading page Domine undefined Error code :-1Description:net::ERR_ClEARTEXT_Not_Permitedenter image description here

  package="com.app"><uses-permission android:name="android.permission.INTERNET" /><application      android:name=".MainApplication"      android:label="@string/app_name"      android:icon="@mipmap/ic_launcher"      android:roundIcon="@mipmap/ic_launcher_round"      android:allowBackup="false"      android:theme="@style/AppTheme"><activity        android:name=".MainActivity"        android:label="@string/app_name"        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"        android:launchMode="singleTask"        android:windowSoftInputMode="adjustResize"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /></application></manifest>```

Error: Unable to determine the current character, it is not a string, number, array, or object in react-native for android

$
0
0

Whenever I run react-native run-android while keeping the emulator running, I get this error. react-native run-ios wroks completely fine.

Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081:ReactNative:Failed to parse React Native CLI configuration: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or objectThe current character read is 'E' with an int value of 69Unable to determine the current character, it is not a string, number, array, or objectline number 1index number 0Error: Invalid attribute nameLine: 16Column: 18Char: .    at error (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/sax/lib/sax.js:651:10)    at strictFail (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/sax/lib/sax.js:677:7)    at SAXParser.write (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/sax/lib/sax.js:1313:13)    at new XmlDocument (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/xmldoc/lib/xmldoc.js:261:15)    at readManifest (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/@react-native-community/cli-platform-android/build/config/readManifest.js:38:10)    at Object.projectConfig (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/@react-native-community/cli-platform-android/build/config/index.js:59:46)    at Object.get project [as project] (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/react-native/node_modules/@react-native-community/cli/build/tools/config/index.js:114:50)    at /Users/yashatreya/Desktop/Realyze/Realyze/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/config/config.js:8:452    at Array.forEach (<anonymous>)    at _objectSpread (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/config/config.js:8:392)^FAILURE: Build failed with an exception.* Where:Script '/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/@react-native-community/cli-platform-android/native_modules.gradle' line: 201* What went wrong:A problem occurred evaluating script.> Failed to parse React Native CLI configuration. Expected running 'npx --quiet --no-install react-native config' command from '/Users/yashatreya/Desktop/Realyze/Realyze' directory to output valid JSON, but it didn't. This may be caused by npx resolving to a legacy global react-native binary. Please make sure to uninstall any global 'react-native' binaries: 'npm uninstall -g react-native react-native-cli' and try again* 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

As indicated in the error message, I tried running npm uninstall -g react-native react-native-cli but it didn’t work.

Info about my environment:

System:    OS: macOS 10.15    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz    Memory: 29.68 MB / 8.00 GB    Shell: 3.2.57 - /bin/bash  Binaries:    Node: 12.13.0 - /usr/local/bin/node    Yarn: 1.19.1 - /usr/local/bin/yarn    npm: 6.12.0 - /usr/local/bin/npm    Watchman: 4.9.0 - /usr/local/bin/watchman  SDKs:    iOS SDK:      Platforms: iOS 13.0, DriverKit 19.0, macOS 10.15, tvOS 13.0, watchOS 6.0  IDEs:    Android Studio: 3.5 AI-191.8026.42.35.5977832    Xcode: 11.0/11A420a - /usr/bin/xcodebuild  npmPackages:    react: 16.9.0 => 16.9.0     react-native: ^0.61.4 => 0.61.4   npmGlobalPackages:    react-native-cli: 2.0.1

android/app/build.gradle below:

apply plugin: "com.android.application"import com.android.build.OutputFileproject.ext.react = [    entryFile: "index.js",    enableHermes: false,  // clean and rebuild if changing]apply from: "../../node_modules/react-native/react.gradle"def enableSeparateBuildPerCPUArchitecture = falsedef enableProguardInReleaseBuilds = falsedef jscFlavor = 'org.webkit:android-jsc:+'def enableHermes = project.ext.react.get("enableHermes", false);android {    compileSdkVersion rootProject.ext.compileSdkVersion    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    defaultConfig {        applicationId "com.realyze"        minSdkVersion 21         targetSdkVersion rootProject.ext.targetSdkVersion        versionCode 1        versionName "1.0"        multiDexEnabled true    }    // rootProject.ext.minSdkVersion    splits {        abi {            reset()            enable enableSeparateBuildPerCPUArchitecture            universalApk false  // If true, also generate a universal APK            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"        }    }    signingConfigs {        debug {            storeFile file('debug.keystore')            storePassword 'android'            keyAlias 'androiddebugkey'            keyPassword 'android'        }    }    buildTypes {        debug {            signingConfig signingConfigs.debug        }        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.debug            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"        }    }    // applicationVariants are e.g. debug, release    applicationVariants.all { variant ->        variant.outputs.each { output ->            // For each separate APK per architecture, set a unique version code as described here:            // https://developer.android.com/studio/build/configure-apk-splits.html            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]            def abi = output.getFilter(OutputFile.ABI)            if (abi != null) {  // null for the universal-debug, universal-release variants                output.versionCodeOverride =                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode            }        }    }}dependencies {    implementation project(':react-native-push-notification')    implementation project(':react-native-sound')    implementation project(':react-native-audio')    implementation 'com.android.support:multidex:2.0.1'    implementation project(':react-native-gesture-handler')    implementation fileTree(dir: "libs", include: ["*.jar"])    implementation "com.facebook.react:react-native:+"  // From node_modules    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'    implementation 'com.google.firebase:firebase-analytics:17.2.0'    implementation 'com.google.firebase:firebase-auth:19.1.0'    implementation project(path: ":@react-native-firebase_auth")    implementation project(path: ":@react-native-firebase_messaging")    implementation project(path: ":@react-native-firebase_database")    implementation project(':react-native-datetimepicker')    implementation project(path: ":@react-native-firebase_firestore")    implementation project(path: ":@react-native-firebase_functions")}    if (enableHermes) {        def hermesPath = "../../node_modules/hermes-engine/android/";        debugImplementation files(hermesPath +"hermes-debug.aar")        releaseImplementation files(hermesPath +"hermes-release.aar")    } else {        implementation jscFlavor    }// }// Run this once to be able to run the application with BUCK// puts all compile dependencies into folder libs for BUCK to usetask copyDownloadableDepsToLibs(type: Copy) {    from configurations.compile    into 'libs'}apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)apply plugin: 'com.google.gms.google-services'

android/build.gradle below :

buildscript {    ext {        buildToolsVersion = "28.0.3"        minSdkVersion = 16        compileSdkVersion = 28        targetSdkVersion = 28    }    repositories {        google()        jcenter()    }    dependencies {        classpath "com.android.tools.build:gradle:3.4.2"        classpath 'com.google.gms:google-services:4.3.2'    }}allprojects {    repositories {        mavenLocal()        maven {            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm            url("$rootDir/../node_modules/react-native/android")        }        maven {            // Android JSC is installed from npm            url("$rootDir/../node_modules/jsc-android/dist")        }        google()        jcenter()        maven { url 'https://jitpack.io' }    }}

Initially I was getting this error: react-native build error: Could not find method implementation() for arguments [jscFlavor] on project ':app' of type org.gradle.api.Project but now I am getting the above.

Native Base blue Status disable not working in drawer React-Native

$
0
0

I am trying to add my custom Status Bar but in the drawer screens the blue bar is not disappearing. Though in other screen everything seems fine. my drawer code is given below:

import React, { Component } from 'react';import { StyleSheet } from 'react-native';import { createDrawerNavigator } from 'react-navigation-drawer';import ProductScreen from '../screens/ProductScreen';export const Drawer = createDrawerNavigator(    {        Product: { screen: ProductScreen }    },    {        navigationOptions: () => ({            drawerLockMode: 'locked-closed',        }),        initialRouteName: "Product",        drawerPosition: 'left'    });

My Product Screen render method is :

<Container style={{ flex: 1}}><Header androidStatusBarColor="#fff" style={{display:'none'}} hidden /><StatusBar barStyle="dark-content" backgroundColor="#fff" />   { this.renderContents() }</Container>

When the page loads it works for few second and again the blue bar appears .I have tried multiple ways suggested in google but no help. thanks in advance.


How solve (Could not initialize class org.codehaus.groovy.reflection.ReflectionCache) issue in react native

$
0
0

$ npx react-native run-androidinfo Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.Jetifier found 864 file(s) to forward-jetify. Using 4 workers...info Starting JS server...info Launching emulator...error Failed to launch the emulator. Reason: Could not start an emulator within 30 seconds.warn Please launch an emulator manually or connect a device. Otherwise, the app may fail to launch.info Installing the app...

FAILURE: Build failed with an exception.

  • What went wrong:Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

  • 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 1m 23s

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

  • What went wrong:Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

  • 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 1m 23s

at checkExecSyncError (child_process.js:629:11)at execFileSync (child_process.js:647:13)at runOnAllDevices (E:\work\react-native\AwesomeProject1\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:39)

React-native app offline with android studio

$
0
0

I'm develeoping react-native app on a computer without internet connection(I can't connect it to the internet),

I have configure the local repository and the android plugin according to android studio guide here

and also linked the gradle localy.

All the configures worked fine but the project is still not compiled, I get unresolved dependencies of the react native modules(example here) that I used.

I'm trying to solve this issue for two weeks and failed.

I didn't find any solution for this yet

The android studio version is 3.5.2 and the gradle version is 5.4.1

Any idea? Any help would be appreciated

Native Base blue Status Bar disable not working in drawer React-Native

$
0
0

I am trying to add my custom Status Bar but in the drawer screens the blue bar is not disappearing. Though in other screen everything seems fine. my drawer code is given below:

import React, { Component } from 'react';import { StyleSheet } from 'react-native';import { createDrawerNavigator } from 'react-navigation-drawer';import ProductScreen from '../screens/ProductScreen';export const Drawer = createDrawerNavigator(    {        Product: { screen: ProductScreen }    },    {        navigationOptions: () => ({            drawerLockMode: 'locked-closed',        }),        initialRouteName: "Product",        drawerPosition: 'left'    });

My Product Screen render method is :

<Container style={{ flex: 1}}><Header androidStatusBarColor="#fff" style={{display:'none'}} hidden /><StatusBar barStyle="dark-content" backgroundColor="#fff" />   { this.renderContents() }</Container>

When the page loads it works for few second and again the blue bar appears .I have tried multiple ways suggested in google but no help. thanks in advance.

react-native-sound does not work in production build for iOS but works within emulator and for production android

$
0
0

I'm working on a React Native application which plays back voicemails. I'm running into an issue with our production app. It does not play back the voicemails on the production iOS or testflight builds, however it will play back on the production build of android as well as the emulator for iOS and Android. I'm relatively new to react-native applications so I'm trying to figure out why this would be occurring.

The app does not crash, it shows the playback as occurring in the UI but no audio is played.

What are specific things to check regarding a production build not being able to play sound?

I am on the current version of react-native-sound which is currently 0.10.9.

Here is my togglePlay function which uses Sound from react-native-sound. I have imported it.

togglePlay() {

  if (this.state.vmLoaded == false) {        if (this.state.vmLoading == true) {            return;        }        if (this.state.vmLoading == false) {            this.setState({ vmLoading: true });            Requester.getVoicemail(this.props.vmData, this.props.token, 'stream')            .then((res) => {                this.setState({                    vmPath: res,                    vmLoaded: true,                });                const vm = new Sound(res, '', (error) => {                    if (error) {                        // Show toast if voicemail did not load                        Toast({ message: 'Failed to load voicemail' });                    } else {                        if (!this.state.vmStarted) {                            this.setState({ vmStarted: true });                        }                        vm.play((success) => {                            if (success) {                                this.setState({                                    vmPlaying: false,                                    currentTime: this.state.vmLength / 1000,                                });                                // Clears the interval timer to keep thread                                // from keeping track of timing                                timer.clearInterval(this, 'playingInt');                            } else {                                // if call recording fails to play, show toast to user                                Toast({ message: 'Failed to play recording' });                            }                        });                        this.setState({ vmPlaying: true });                        // if loaded successfully, set the instance of Sound as STATE vm                        // allowing calls to the instance via this.state.vm                        // ie: this.state.vm.play() will initiate playing the sound                        this.setState({                            // set instance of Sound to state                            vm,                            // set full length of recording to state                            vmLength: vm.getDuration(),                            // set current playing time of recording to state (new, so zero)                            currentTime: 0,                            // interval is still null until sound is played                            interval: null,                            // sound starts off paused (no audio)                            vmPlaying: true,                            // Finally, the recording has been loaded, setting                            // this so another instance is not created on                            // rerender (see above IF statements)                            vmLoaded: true,                            vmLoading: false,                        });                    }                });            }).then(() => {                timer.clearInterval(this, 'playingInt');                interval: timer.setInterval(this, 'playingInt', () => {                    this.state.vm.getCurrentTime((seconds) => {                        this.setState({ currentTime: seconds });                    });                }, 1000);            });        }    } else if (this.state.vmLoaded == true) {        if (this.state.vmPlaying == true) {            this.state.vm.pause();            this.setState({ vmPlaying: false });            timer.clearInterval(this, 'playingInt');        } else {            this.state.vm.play();            this.setState({ vmPlaying: true });            timer.clearInterval(this, 'playingInt');            interval: timer.setInterval(this, 'playingInt', () => {                this.state.vm.getCurrentTime((seconds) => {                    this.setState({ currentTime: seconds });                });            }, 1000);        }    }}

Please let me know if other information would be helpful in debugging this.

Thank you

React native bottom tab bar pushing itself up when opening keyboard

$
0
0

We are using createBottomTabNavigator. In one of the tab contains search bar at the top. While clicking on that search bar, we are opening the keyboard. But the keyboard pushing up the bottom tab bar also. We need the bottom tab bar remains at the bottom when opening keyboard.

  1. One of the solution I have tried is, in android manifest, I have changed android:windowSoftInputMode="adjustPan" or "adjustNothing". It is working fine as expected. But we are using chat layout in another tab which needs "adjustResize". So I have to keep "adjustResize" for windowSoftInputMode.
  2. As another solution, I tried to change windowSoftInputMode inside component itself. SO I have tried with this - https://www.npmjs.com/package/react-native-android-keyboard-adjust. But no use.
  3. As another one, I tried to create a TabBarComponent like mentioned here https://github.com/react-navigation/react-navigation/issues/618. But not working as expected.
const SignedIn = createBottomTabNavigator(  {    Followers: {      screen: FollowerStack,      ...    },    Search: {      screen: SearchStack,    },    Home: {      screen: HomeStack,    },    Bookmarks: {      screen: BookmarkStack,    },    Profile: {      screen: ProfileStack,    }  },  {    initialRouteName: "Home",    tabBarPosition: 'bottom',    swipeEnabled: false,    animationEnabled: false,    tabBarOptions: {      keyboardHidesTabBar: true,      showIcon: true,      showLabel: false,      activeTintColor: "red",      inactiveTintColor: "gray",      adaptive: true,      safeAreaInset: {        bottom: "always"      },      style: {        position: 'relative',        backgroundColor: "#F9F8FB",        height: TAB_NAVIGATOR_DYNAMIC_HEIGHT,        paddingTop: DeviceInfo.hasNotch() ? "5%" : "0%",        minHeight: TAB_NAVIGATOR_DYNAMIC_HEIGHT,        width: '100%',        bottom: 0      }    }  });
  1. Is there any other properties existed for making the bottom tab bar sticky at the bottom?or
  2. Is it possible to change the android manifest windowSoftInputMode from inside component?Please comment below if you required any other code part for reference. Thanks for any help.

Probleme with react native and couchbase lite

$
0
0

slm, i have a problem storing the following list of objects from my javaScript (react native) code in a Couchbase lite database. I can't get it in my native java module.

[{"name": "hotel_Azalay"}, {"adress": "capital"}, {"city": "kiffa"}]

I want all key/value pairs to store in a document.

how can i retrieve the elements of this list in my java code and save them directly in the database?

Why aren't any of my "react-native" commands not working anymore?

$
0
0

I was working in my React Native file when I noticed that whenever I typed any command(except help) that begun with "react-native" I would receive an error that states:

error Unrecognized command "link".

info Run "react-native --help" to see a list of all available commands.

I got this error when I tried both "react-native run-android" and "react-native link". I have no idea what's causing this so I would really appreciate any suggestions as to what to try to remedy this. I also have't linked any of my actual code as I have no idea what part of my project could be the cause of this. I'd love to hear any suggestions that anyone has for me.


how to use LinearGradient for react tab navigator tabs

$
0
0

I have a react tabnavigator which i used it from ReactNavigation(v2) component:

const Tab = createMaterialTopTabNavigator({  Nearest: {    screen: Nearest, navigationOptions: {      tabBarLabel: 'myprofile'    }  },  Recomanded: {    screen: Recomanded, navigationOptions: {      tabBarLabel: 'recomanded'    }  },  Home: {    screen: Hotest, navigationOptions: {      tabBarLabel: 'hotest'    }  },},  {    tabBarOptions: {      labelStyle: {        fontSize: 12,         fontFamily:"IRANSans"      },      tabStyle: {        backgroundColor: '#ef6102',      }    }  });

now i want to use linear gradient for Tabs color but i couldn't find any way to do it!...how its possible ? how can i take the tabs inside this tag:

<LinearGradient  colors={['#EF7D2F', '#C8191A']}>..here..</LinearGradient>

Unable to build react native app after ejecting from expo

$
0
0

The Kotlin Gradle plugin was loaded multiple times in different subprojects, which is not supported and may break the build. This might happen in subprojects that apply the Kotlin plugins with the Gradle 'plugins { ... }' DSL if they specify explicit versions, even if the versions are equal.Please add the Kotlin plugin to the common parent project or the root project, then remove the versions in the subprojects.If the parent project does not need the plugin, add 'apply false' to the plugin line.See: https://docs.gradle.org/current/userguide/plugins.html#sec:subprojects_plugins_dslThe Kotlin plugin was loaded in the following projects: ':expo-error-recovery', ':react-native-webview'

Task :react-native-threads:compileDebugJavaWithJavac FAILED 297 actionable tasks: 2 executed, 295 up-to-date /Users/krishnalahoti/IdeaProjects/pretech-UI/node_modules/react-native-threads/android/src/main/java/com/reactlibrary/ThreadBaseReactPackage.java:52: error: cannot find symbol new DevSettingsModule(catalystApplicationContext, reactInstanceManager.getDevSupportManager()) ^ symbol: class DevSettingsModule location: class ThreadBaseReactPackage 1 error

FAILURE: Build failed with an exception.

  • What went wrong:Execution failed for task ':react-native-threads: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. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 19s

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081/Users/krishnalahoti/IdeaProjects/pretech-UI/node_modules/react-native-threads/android/src/main/java/com/reactlibrary/ThreadBaseReactPackage.java:52: error: cannot find symbol new DevSettingsModule(catalystApplicationContext, reactInstanceManager.getDevSupportManager()) ^ symbol: class DevSettingsModule location: class ThreadBaseReactPackage1 error

FAILURE: Build failed with an exception.

  • What went wrong:Execution failed for task ':react-native-threads: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. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 19s

at checkExecSyncError (child_process.js:611:11)at execFileSync (child_process.js:629:15)at runOnAllDevices (/Users/krishnalahoti/IdeaProjects/pretech-UI/node_modules/react-native/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:39)at processTicksAndRejections (internal/process/task_queues.js:97:5)

npm ERR! code ELIFECYCLEnpm ERR! errno 1npm ERR! @ android: react-native run-androidnpm ERR! Exit status 1npm ERR! npm ERR! Failed at the @ android script.npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:npm ERR! /Users/krishnalahoti/.npm/_logs/2020-06-16T08_26_02_354Z-debug.log

margin or borderWidth properties don't work correctly in react native

$
0
0

I have multiple blocks with the same style:

blocksContainer:{ // the container of all blocks    flexDirection: "row",    flexWrap: "wrap",},block:{    width: SCREEN_WIDTH /4,    height: SCREEN_HEIGHT /12,    backgroundColor: "#2d2d2d",    borderWidth: .5,    borderColor: "#6faaa3"},

and this is the result:

my blocks

as you can see, border gradually disappears and at some points doubles.I also tried margin instead of borderWidth, but I got the same result!does it have something to do with react native or my emulator?note that it works correctly when I have less blocks:my app with less blocks

react native scrollview not scrolling on android

$
0
0

I have the following component:

export default class StoreComponent extends Component {  render() {    return (<View style={styles.container}><ScrollView contentContainerStyle={styles.scroll}><StoreCarouselComponent /><StoreDiscountComponent /><StoreDetailsComponent /></ScrollView></View>    );  }}

with this style

import { StyleSheet, Dimensions, } from 'react-native';const styles = StyleSheet.create({  container: {    flex: 1,    backgroundColor: '#ffffff',  },  scroll: {    flex: 1,    flexDirection: 'row',    justifyContent: 'center'  },  image: {    width: Dimensions.get('window').width,    height: 350,  },  box: {    width: Dimensions.get('window').width - 30,    position: 'absolute',    shadowColor: '#000000',    shadowOpacity: 0.34,    shadowRadius: 5,    shadowOffset: {      width: 0,      height: 10    },    elevation: 10,    borderTopLeftRadius: 10,    borderTopRightRadius: 10,    borderBottomLeftRadius: 10,    borderBottomRightRadius: 10,    borderColor: 'lightgrey',    backgroundColor: '#ffffff',    padding: 10,    marginTop: 410,  },  boxDiscount: {    width: Dimensions.get('window').width - 30,    position: 'absolute',    shadowColor: '#000000',    shadowOpacity: 0.34,    shadowRadius: 5,    shadowOffset: {      width: 0,      height: 10    },    elevation: 10,    borderTopLeftRadius: 10,    borderTopRightRadius: 10,    borderBottomLeftRadius: 10,    borderBottomRightRadius: 10,    borderColor: 'lightgrey',    backgroundColor: '#253241',    padding: 10,    marginTop: 320,  },  title: {    fontSize: 30  },  distance: {    fontSize: 20,    color: '#767676'  },  distanceElement: {    fontSize: 20,    color: '#44D9E6'  },  address: {    fontSize: 20,    color: '#767676'  },  category: {    fontSize: 20,    color: '#767676',  },  categoryElement: {    fontSize: 20,    color: '#44D9E6',  },  hr: {    borderBottomColor: 'lightgrey',    borderBottomWidth: 1,  },  icons: {    flex: 1,    flexDirection: 'row',    justifyContent: 'center',  }});export default styles;

my scrollview works on ios but on android don't and I don't understand why

here a an image of the app and as you can see I need to scroll on android:

enter image description here

How can i set elevation shadow only on the bottom on react native

$
0
0

I'm trying to add a shadow on the bottom of a view, but i don't how to do it on Android. With elevation it put a shadow also on the top. Is there a way to do it like on iOS?

Here's my code:

export function makeElevation(elevation) {const iosShadowElevation = {    shadowOpacity: 0.0015 * elevation + 0.18,    shadowRadius: 0.5 * elevation,    shadowOffset: {        height: 0.6 * elevation,    },};const androidShadowElevation = {    elevation,};return Platform.OS === 'ios' ? iosShadowElevation : androidShadowElevation;

}

left: iOS (expected)

right: Android

EDIT: The only "fake" solution i found is to use react-native-linear-gradient instead to create a custom shadow

IOS/ANDROID

Viewing all 28476 articles
Browse latest View live


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