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

Unable to start android react-native app: Error: spawnSync ~/Library/Android/sdk/platform-tools/adb ENOENT

$
0
0

I'm attempting to get started with a react native project I've inherited.

My steps in running are to:

  1. npx react-native start - this works
  2. Open an android emulator (API 28)
  3. Open a new bash
  4. npx react-native run-android

I get the error:

warn Failed to connect to development server using "adb reverse": spawnSync ~/Library/Android/sdk/platform-tools/adb ENOENT info Starting the app on "emulator-5554"... error Failed to start the app. Run CLI with --verbose flag for more details. Error: spawnSync ~/Library/Android/sdk/platform-tools/adb ENOENT

I'm surprised by the ENOENT, as I can manually run the file at that location:~/Library/Android/sdk/platform-tools/adb

My path was set up as noted in the Development guide: https://reactnative.dev/docs/environment-setup

export ANDROID_HOME=$HOME/Library/Android/sdk export PATH=$PATH:$ANDROID_HOME/emulator export PATH=$PATH:$ANDROID_HOME/tools export PATH=$PATH:$ANDROID_HOME/tools/bin export PATH=$PATH:$ANDROID_HOME/platform-tools

Why might it fail on locating ~/Library/Android/sdk/platform-tools/adb?


How to implement geocoder with @react-native-mapbox-gl/maps library in react native

$
0
0

i'm trying to implement Geocoder with the @react-native-mapbox-gl/maps library as it's the sugestion in the official Mapbox's website for react native apps.

My map is fully operational, but when comes to Geocoder I couldn't find a proper library. Tried some react libraries but I got some errors and don't know where to go.I've tried a lot already and couldn't get it to work.Already tested the libraries react-mapbox-gl-geocoder, @mapbox/mapbox-gl-geocoder and react-mui-mapbox-geocoder (can't post more then 8 links so just remove the space: www.npmjs.com /package/react-mui-mapbox-geocoder).Even tried react-map-gl-geocoder with react-map-gl library that is deprecated to see if would work, as I've seen some examples with geocoder, but that didn't work as well.

Here's my code without the Geocoder libraries:

import React, { Component, useState } from 'react';import {   View,   Text,   StyleSheet,   PermissionsAndroid,  TextInput,  Keyboard,} from 'react-native';import Geolocation from "@react-native-community/geolocation";import MapboxGL from '@react-native-mapbox-gl/maps';import Colors from '../../styles/colors';// Variáveisgranted = 1;MapboxGL.setAccessToken('Mapbox token');MapboxGL.setConnected(true);async function requestLocationPermission() {    try {        granted = await PermissionsAndroid.request(            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,            {                title: 'App',                message:'Necessita de permissão da sua localização para mostrar o mapa.',                buttonNeutral: 'Perguntar mais tarde',                buttonNegative: 'Cancel',                buttonPositive: 'OK',            },        );    } catch (err) {        console.warn(err);    }}export default function Home({ navigation }) {    const permissaoLocalizacao = requestLocationPermission()    const [position, setPosition] = useState({        latitude: 0,        longitude: 0    });    const [error, setError] = useState("");    const getPosition = () => {        Geolocation.getCurrentPosition(        pos => {            setError("");            setPosition({            latitude: pos.coords.latitude,            longitude: pos.coords.longitude            });        },        e => setError(e.message)        );    };    const onMapPress = (event) => {    }    if (permissaoLocalizacao) {        if (!position.longitude) {            getPosition();        }        if (error) {            console.log("error")            return (<View style={styles.container}>                {/* alert('Sair do aplicativo'); */}</View>            )        }        return (<View style={styles.container}><MapboxGL.MapView                style={styles.map}                onPress={onMapPress}><MapboxGL.Camera                    zoomLevel={16}                    centerCoordinate={[position.longitude, position.latitude]}                /><MapboxGL.PointAnnotation                    id="PosicaoAtual"                    coordinate={[position.longitude, position.latitude]}><View style={styles.annotationContainer}><View style={styles.annotationFill} /></View></MapboxGL.PointAnnotation></MapboxGL.MapView></View>        );    }else{        return(<View style={styles.container}><Text>Necessário permissão da localização</Text></View>        );    }}const styles = StyleSheet.create({  container: {    flex: 1,    backgroundColor: Colors.white,  },  map: {    flex: 1,  },  annotationContainer: {    width: 30,    height: 30,    alignItems: 'center',    justifyContent: 'center',    backgroundColor: 'white',    borderRadius: 15,  },  annotationFill: {    width: 30,    height: 30,    borderRadius: 15,    backgroundColor: Colors.primary,    transform: [{ scale: 0.8 }],  }});

And this is my package.json, it's a little polluted, cause I've tried so many things already:

{"name": "mapbox","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","test": "jest","lint": "eslint ."  },"dependencies": {"@mapbox/mapbox-gl-geocoder": "^4.5.1","@react-native-community/geolocation": "^2.0.2","@react-native-community/masked-view": "^0.1.6","@react-native-mapbox-gl/maps": "^7.2.0","@react-navigation/bottom-tabs": "^5.4.2","@react-navigation/drawer": "^5.5.0","@react-navigation/native": "^5.0.6","@react-navigation/stack": "^5.0.6","react": "16.11.0","react-map-gl": "^5.2.5","react-map-gl-geocoder": "^2.0.11","react-mapbox-gl-geocoder": "^1.1.0","react-mui-mapbox-geocoder": "^1.1.1","react-native": "0.62.2","react-native-geolocation-service": "^4.0.0","react-native-gesture-handler": "^1.6.0","react-native-reanimated": "^1.7.0","react-native-safe-area-context": "^0.7.3","react-native-safe-area-view": "^1.1.0","react-native-screens": "^2.0.0-beta.10","react-native-vector-icons": "^6.6.0","react-navigation": "^4.1.1",  },"devDependencies": {"@babel/core": "^7.9.6","@babel/runtime": "^7.9.6","@react-native-community/eslint-config": "^1.1.0","babel-jest": "^26.0.1","eslint": "^7.0.0","jest": "^26.0.1","metro-react-native-babel-preset": "^0.59.0","react-test-renderer": "16.11.0"  },"jest": {"preset": "react-native"  }}

My android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    ext {        buildToolsVersion = "28.0.3"        minSdkVersion = 16        compileSdkVersion = 28        targetSdkVersion = 28    }    repositories {        google()        jcenter()    }    dependencies {        classpath("com.android.tools.build:gradle:3.5.2")        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}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://www.jitpack.io' }    }}

My android/setting.gradle

rootProject.name = 'mapbox'// MapBoxinclude ':@react-native-mapbox-gl_maps'project(':@react-native-mapbox-gl_maps').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-mapbox-gl/maps/android/rctmgl')// Vector Iconsinclude ':react-native-vector-icons'project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)include ':app'

My android/app/build.gradle

apply plugin: "com.android.application"import com.android.build.OutputFile/** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ *   // the name of the generated asset file containing your JS bundle *   bundleAssetName: "index.android.bundle", * *   // the entry file for bundle generation. If none specified and *   // "index.android.js" exists, it will be used. Otherwise "index.js" is *   // default. Can be overridden with ENTRY_FILE environment variable. *   entryFile: "index.android.js", * *   // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format *   bundleCommand: "ram-bundle", * *   // whether to bundle JS and assets in debug mode *   bundleInDebug: false, * *   // whether to bundle JS and assets in release mode *   bundleInRelease: true, * *   // whether to bundle JS and assets in another build variant (if configured). *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants *   // The configuration property can be in the following formats *   //         'bundleIn${productFlavor}${buildType}' *   //         'bundleIn${buildType}' *   // bundleInFreeDebug: true, *   // bundleInPaidRelease: true, *   // bundleInBeta: true, * *   // whether to disable dev mode in custom build variants (by default only disabled in release) *   // for example: to disable dev mode in the staging build type (if configured) *   devDisabledInStaging: true, *   // The configuration property can be in the following formats *   //         'devDisabledIn${productFlavor}${buildType}' *   //         'devDisabledIn${buildType}' * *   // the root of your project, i.e. where "package.json" lives *   root: "../../", * *   // where to put the JS bundle asset in debug mode *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * *   // where to put the JS bundle asset in release mode *   jsBundleDirRelease: "$buildDir/intermediates/assets/release", * *   // where to put drawable resources / React Native assets, e.g. the ones you use via *   // require('./image.png')), in debug mode *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * *   // where to put drawable resources / React Native assets, e.g. the ones you use via *   // require('./image.png')), in release mode *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to *   // date; if you have any other folders that you want to ignore for performance reasons (gradle *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ *   // for example, you might want to remove it from here. *   inputExcludes: ["android/**", "ios/**"], * *   // override which node gets called and with what additional arguments *   nodeExecutableAndArgs: ["node"], * *   // supply additional arguments to the packager *   extraPackagerArgs: [] * ] */project.ext.react = [    enableHermes: false,  // clean and rebuild if changing]apply from: "../../node_modules/react-native/react.gradle"/** * Set this to true to create two separate APKs instead of one: *   - An APK that only works on ARM devices *   - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */def enableSeparateBuildPerCPUArchitecture = false/** * Run Proguard to shrink the Java bytecode in release builds. */def enableProguardInReleaseBuilds = false/** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US.  Note that * this variant is about 6MiB larger per architecture than default. */def jscFlavor = 'org.webkit:android-jsc:+'/** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and mirrored here.  If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */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.mapbox"        minSdkVersion rootProject.ext.minSdkVersion        targetSdkVersion rootProject.ext.targetSdkVersion        versionCode 1        versionName "1.0"        multiDexEnabled true    }    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"        }    }    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"    }    // 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 fileTree(dir: "libs", include: ["*.jar"])    //noinspection GradleDynamicVersion    implementation "com.facebook.react:react-native:+"  // From node_modules    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"    // React native screens    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'    // MapBox    implementation project(':@react-native-mapbox-gl_maps')    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {      exclude group:'com.facebook.fbjni'    }    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {        exclude group:'com.facebook.flipper'    }    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {        exclude group:'com.facebook.flipper'    }    if (enableHermes) {        def hermesPath = "../../node_modules/hermes-engine/android/";        debugImplementation files(hermesPath +"hermes-debug.aar")        releaseImplementation files(hermesPath +"hermes-release.aar")    } else {        implementation jscFlavor    }    compile 'com.android.support:multidex:1.0.1'    // Vector Icons    compile project(':react-native-vector-icons')}// 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)// Vector Iconsapply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

And the MainApplication;

package com.mapbox;import android.app.Application;import android.content.Context;import com.facebook.react.PackageList;import com.facebook.react.ReactApplication;import com.oblador.vectoricons.VectorIconsPackage;import com.facebook.react.ReactInstanceManager;import com.facebook.react.ReactNativeHost;import com.facebook.react.ReactPackage;import com.facebook.soloader.SoLoader;import com.mapbox.rctmgl.RCTMGLPackage; // Mapboximport com.oblador.vectoricons.VectorIconsPackage;  // Vector Iconsimport java.lang.reflect.InvocationTargetException;import java.util.List;public class MainApplication extends Application implements ReactApplication {  private final ReactNativeHost mReactNativeHost =      new ReactNativeHost(this) {        @Override        public boolean getUseDeveloperSupport() {          return BuildConfig.DEBUG;        }        @Override        protected List<ReactPackage> getPackages() {          @SuppressWarnings("UnnecessaryLocalVariable")          List<ReactPackage> packages = new PackageList(this).getPackages();          // Packages that cannot be autolinked yet can be added manually here, for example:          // packages.add(new MyReactNativePackage());          //new VectorIconsPackage()  // Vector Icons          return packages;        }        @Override        protected String getJSMainModuleName() {          return "index";        }      };  @Override  public ReactNativeHost getReactNativeHost() {    return mReactNativeHost;  }  @Override  public void onCreate() {    super.onCreate();    SoLoader.init(this, /* native exopackage */ false);    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());  }  /**   * Loads Flipper in React Native templates. Call this in the onCreate method with something like   * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());   *   * @param context   * @param reactInstanceManager   */  private static void initializeFlipper(      Context context, ReactInstanceManager reactInstanceManager) {    if (BuildConfig.DEBUG) {      try {        /*         We use reflection here to pick up the class that initializes Flipper,        since Flipper library is not available in release mode        */        Class<?> aClass = Class.forName("com.mapbox.ReactNativeFlipper");        aClass            .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)            .invoke(null, context, reactInstanceManager);      } catch (ClassNotFoundException e) {        e.printStackTrace();      } catch (NoSuchMethodException e) {        e.printStackTrace();      } catch (IllegalAccessException e) {        e.printStackTrace();      } catch (InvocationTargetException e) {        e.printStackTrace();      }    }  }}

I don't know if this react libraries could work, but this are the errors that I'm facing:

-I replaced the project directory with to be more clean

-> Importing react-mapbox-gl-geocoder:

-It first occurred the missing of 'events' and 'http' libraries, then I added them and couldn't resolve this one.

error: Error: While trying to resolve module `http` from file `<projectfolder>\node_modules\react-mapbox-gl-geocoder\dist\index.js`, the package `<projectfolder>\node_modules\http\package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`<projectfolder>\node_modules\http\index`. Indeed, none of these files exist:  * <projectfolder>\node_modules\http\index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)  * <projectfolder>\node_modules\http\index\index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)    at ResolutionRequest.resolveDependency (<projectfolder>\node_modules\metro\src\node-haste\DependencyGraph\ResolutionRequest.js:65:15)    at DependencyGraph.resolveDependency (<projectfolder>\node_modules\metro\src\node-haste\DependencyGraph.js:287:16)    at Object.resolve (<projectfolder>\node_modules\metro\src\lib\transformHelpers.js:267:42)    at <projectfolder>\node_modules\metro\src\DeltaBundler\traverseDependencies.js:434:31    at Array.map (<anonymous>)    at resolveDependencies (<projectfolder>\node_modules\metro\src\DeltaBundler\traverseDependencies.js:431:18)    at <projectfolder>\node_modules\metro\src\DeltaBundler\traverseDependencies.js:275:33    at Generator.next (<anonymous>)    at asyncGeneratorStep (<projectfolder>\node_modules\metro\src\DeltaBundler\traverseDependencies.js:87:24)    at _next (<projectfolder>\node_modules\metro\src\DeltaBundler\traverseDependencies.js:107:9)

-> Importing @mapbox/mapbox-gl-geocoder:

This occures in build:

[Sat May 23 2020 21:41:54.544]  WARN     Require cycle: node_modules\@react-native-mapbox-gl\maps\javascript\index.js -> node_modules\@react-native-mapbox-gl\maps\javascript\components\annotations\Annotation.js -> node_modules\@react-native-mapbox-gl\maps\javascript\index.jsRequire cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.

And this in the app:

app error

So I added the 'expo-random' and 'nonoid' libraries, but then it ask's me for '@unimodules/core', and then '@unimodules/react-native-adapter' and another error, so I stopped.

-> Importing react-mui-mapbox-geocoder

Gives me an arror to update Autosuggest library.

-> Importing react-map-gl-geocoder with map-gl

This occures in build:

[Sat May 23 2020 16:54:57.817]  WARN     Require cycle: node_modules\viewport-mercator-project\dist\es5\web-mercator-viewport.js -> node_modules\viewport-mercator-project\dist\es5\fit-bounds.js -> node_modules\viewport-mercator-project\dist\es5\web-mercator-viewport.jsRequire cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.

And this in the app.app error

If you see something else wrong or that could be better, please let me know. I'm still learning react native and I may have misunderstood something.Hope we can find a solution and that this helps others to.

Database doesn't exist/not being loaded in built app with Expo

$
0
0

for the last couple of months I've been working on my first app project with react native and Expo.

I'm ready to finally launch my app but I'm having one big issue: The app uses a premade sqlite database to read and update information, this database gets loaded into the app the first time it launches or if the version has been updated (via a simple variable). I tested the app with no issues via the Expo Client but, now that I'm trying it in a phone (via an apk) there's no db and I have no clue why it's not working

Here's the code that loads the db:

FileSystem.downloadAsync(  Asset.fromModule(require('../databases/programs.db')).uri,  `${FileSystem.documentDirectory}SQLite/programs-${version}.db`).then(() => {  programsDB = SQLite.openDatabase(`programs-${version}.db`);  loadDB(loaded);});

I have this in metro.config.js:

module.exports = {  resolver: {    blacklistRE: blacklist([/amplify\/#current-cloud-backend\/.*/]),    assetExts: ["db", "ttf", "png", "jpg"]  },  transformer: {    getTransformOptions: async () => ({      transform: {        experimentalImportSupport: false,        inlineRequires: false,      },    }),  },};

And this in app.json

"assetBundlePatterns": ["src/library/assets/**/*","src/library/databases/*","src/library/fonts/*"],"packagerOpts": {"assetExts": ["db"]},

I've tried both with

require('../databases/programs.db'

and

require('library/databases/programs.db'

After the app tries to load stuff from the db I get the following error:"Directory for /data/user/0/com.company.myApp/files/SQLite/programs-2020052401.db doesn't exist"

I also tried changing the source db to download from .db to .mp4 after an answer I read elsewhere but it doesn't do it either.

Any ideas? This is the last hurdle before I can finally launch my app.

EdgeLight: Screen borders are not going beyond the notch and softkeys in react native

$
0
0

I am just trying to implement "edge light" Ref in react native.

I have this below code to achieve it.

<Layout style={{ flex: 1, paddingTop: 18, paddingBottom: 18, paddingLeft: 28, paddingRight: 28, borderWidth: 10, borderColor: '#36ABA5', justifyContent: 'center', backgroundColor: '#000', color: '#fff' }}> // All my code </Layout>

This seems to be working fine for the mobiles which are having straigh screens. But I am facing 2 issues,

  1. The same is not working when the mobile has notch or the mobile's softkeys are enabled.
  2. In Honor 8x the border itself is not coming when softkeys are disabled, when those are enabled, the border comes above the softkeys.

I tried calculating the window height, screen height and put the border. It seems to be not happening.

In Straight phone

In Straight phone:

In Notch phone:

In Notch phone:

In Softkeys enabled:

enter image description here

In Softkeys disabled:

In Softkeys disabled:

Wanted similar to this, but not colorful/ Expected Results:

Wanted similar to this, but not colorful/ Expected Results:

Buggy Collapsible Header Tabs in React Native (Android)

$
0
0

I am trying to build a collapsible header tab.

I finally found this one Collapsible Header Tabs Snack which worked perfectly as base code. It worked as expected on IOS, but I had not confirmed the Android version yet. now that I look at it, it's very buggy. This can be seen in the above snack by running in android.

Screen preview

The Header scroll is very buggy (fluctuation) until the tabs clamp onto the top but then the scroll is smooth.I am guessing that there is a problem with the sticky scroll which has animated scroll views and animated views.

I tried adding scrollToOverflowEnabled = {true} overScrollMode={'never'} but it didn't help.

Any help would be appreciated. Thanks

React native android can not find com.android.tools.build:gradle:3.6.3

$
0
0

Any people met the issue Could not resolve all artifacts for configuration ':react-native-fast-image:classpath' and can not find com.android.tools.build:gradle:3.6.3 ? I try open the project structure and see the gradle plugin tool is 3.6.3 and the gradle version is 5.4.6 but i dont know what happen now

The build.gradle file :

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    /*ext {        buildToolsVersion = "28.0.2"        minSdkVersion = 16        compileSdkVersion = 28        targetSdkVersion = 27        supportLibVersion = "28.0.0"    }*/    repositories {        jcenter()        google()        maven {            url 'https://maven.google.com/'            name 'Google'        }        mavenCentral()    }    dependencies {        classpath 'com.android.tools.build:gradle:3.5.0'        classpath 'com.google.gms:google-services:4.0.1'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        configurations.all {            resolutionStrategy.eachDependency { details ->                def requested = details.requested                if (requested.group == 'com.google.android.gms') {                    details.useVersion '12.0.1'                }                if (requested.group == 'com.google.firebase') {                    details.useVersion '12.0.1'                }            }        }        mavenLocal()        mavenCentral()        google()        jcenter()        maven {            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm            url "$rootDir/../node_modules/react-native/android"        }        maven {            url 'https://maven.google.com/'            name 'Google'        }    }}subprojects {    project.configurations.all {        resolutionStrategy.eachDependency { details ->            if (details.requested.group == 'com.android.support'&& !details.requested.name.contains('multidex') ) {                details.useVersion "27.1.1"            }        }    }}ext {    buildToolsVersion = "28.0.3"    minSdkVersion = 16    compileSdkVersion = 28    targetSdkVersion = 28    supportLibVersion = "28.0.0"    googlePlayServicesVersion = "15.0.1"    androidMapsUtilsVersion = "0.5+"}project.ext {    excludeAppGlideModule = true}/*task wrapper(type: Wrapper) {    gradleVersion = '4.7'    distributionUrl = distributionUrl.replace("bin", "all")}*/

Gradle warning :while build Android using Expo it shows Could not find google-services.json

$
0
0

when I run expo build:androidI always get the error

Could not find google-services.json while looking in [src/nullnull/debug, src/debug/nullnull, src/nullnull, src/debug, src/nullnullDebug]registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)

I'm using firebase so I downloaded google.services.json file from "Your apps" firebase project console, and I have put the directory for the google.services.json file in app.json.still getting the error!!

I would appreciate it if you help me .. thanks in advance

app.json:

{"expo": {"sdkVersion": "36.0.0","android": {"package": "com.myApp.bookShelf","versionCode": 1,"googleServicesFile": "./google-services.json","config": {"googleSignIn": {"apiKey": "Copied from google.services"        }      }    },"web": {"config": {"firebase": {--- }      }    }  }}

google-services.json :

{"project_info": {---},"client": [    {"client_info": {"mobilesdk_app_id": "--","android_client_info": {"package_name": "com.myApp.bookShelf"        }      },

expo build:android error screenshot

React Native offline App using react-native-sqlite-storage

$
0
0

I am new to react native. I want to build an offline react native app for storing user data (Basic user details, user personal documents, images, etc). I already gone through some documents about react-native-sqlite-storage and I would like to integrate it. But not sure,

  1. If I can recover all the user data when user delete application data
  2. What is advantage of using react-native-sqlite-storage than redux-persist for offline app development?

How to make smartphone advertise for BLE in react-native?

$
0
0

I am developing an app and I want the smartphone that have the app installed should sacn eachother by emiiting some kind of advertised data.I have tried react-native-ble-plx but it is not working. Any other suggestions as to how it can be achieved?

error Option "--entry-file" is missing. Run CLI with --verbose flag for more details

$
0
0

I tried to install native react and when I enter the command npm run android-windows there;s error.

How to solve this?

This is my packages.json

{"name": "Fyp","version": "0.0.1","private": true,"scripts": {"start": "react-native start","test": "jest","lint": "eslint .","android-windows": "react-native bundle --platform android --dev false npm run android-windows--entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android" },"dependencies": {"react": "16.8.6","react-native": "0.60.5" },"devDependencies": {"@babel/core": "7.5.5","@babel/runtime": "7.5.5","@react-native-community/eslint-config": "0.0.3","babel-jest": "24.9.0","eslint": "6.3.0","jest": "24.9.0","metro-react-native-babel-preset": "0.54.1","react-test-renderer": "16.8.6" },"jest": {"preset": "react-native" }}

This is the error

error Option "--entry-file" is missing. Run CLI with --verbose flag for more details.Error: Option "--entry-file" is missing at C:\Users\user\Fyp\node_modules\react-native\node_modules@react-native-community\cli\build\tools\assertRequiredOptions.js:51:13 at Array.forEach () at assertRequiredOptions (C:\Users\user\Fyp\node_modules\react-native\node_modules@react-native-community\cli\build\tools\assertRequiredOptions.js:40:11) at Command.handleAction (C:\Users\user\Fyp\node_modules\react-native\node_modules@react-native-community\cli\build\cliEntry.js:159:42) at Command.listener (C:\Users\user\Fyp\node_modules\commander\index.js:315:8) at Command.emit (events.js:209:13) at Command.parseArgs (C:\Users\user\Fyp\node_modules\commander\index.js:651:12) at Command.parse (C:\Users\user\Fyp\node_modules\commander\index.js:474:21) at setupAndRun (C:\Users\user\Fyp\node_modules\react-native\node_modules@react-native-community\cli\build\cliEntry.js:210:24) at Object.run (C:\Users\user\Fyp\node_modules\react-native\node_modules@react-native-community\cli\build\cliEntry.js:173:11)npm ERR! code ELIFECYCLEnpm ERR! errno 1npm ERR! Fyp@0.0.1 android-windows: react-native bundle --platform android --dev false npm run android-windows--entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-androidnpm ERR! Exit status 1npm ERR!npm ERR! Failed at the Fyp@0.0.1 android-windows 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! C:\Users\user\AppData\Roaming\npm-cache_logs\2019-09-06T15_03_19_543Z-debug.log

No error - sending data from phone app to hm-10 BLE module not working

$
0
0

I have created a react Native app and I am using the react-native-ble-manager library.https://www.npmjs.com/package/react-native-ble-manager

I am using the hm-10 BLE module with an arduino nano, with this code ->

#include <SoftwareSerial.h>#define LED_PIN 13SoftwareSerial mySerial(0, 1); // RX, TX  // Connect HM10      Arduino Uno//     Pin 1/TXD          Pin 7//     Pin 2/RXD          Pin 8void setup() {    Serial.begin(9600);  // If the baudrate of the HM-10 module has been updated,  // you may need to change 9600 by another value  // Once you have found the correct baudrate,  // you can update it using AT+BAUDx command   // e.g. AT+BAUD0 for 9600 bauds  mySerial.begin(9600);}void loop() {    int c;  int s;  if (Serial.available()) {    s = Serial.read();    Serial.println("Got other input:");    Serial.println(c);  }  if (mySerial.available()) {    c = mySerial.read();      Serial.println("Got input:");    Serial.println(c);  }}

http://acoptex.com/uploads/HM10ServicesandCharacteristics.pdf

from reading the document above on the HM-10 I am connecting to the third service.In my react app I am able to find and save the service uuid and characteristic uuid that match the docs.

https://github.com/Polidea/react-native-ble-plx/wiki/Characteristic-Writing

from the document above, on the react-native-ble-manager doc for writing to the device I am using this method in my code

deviceObject.writeCharacteristicWithoutResponseForService(writeService, writeChar, encodedString);

I can send data through The arduino serial monitor and the code prints values, but when I send data from my phone app with the method above, no values are printed in the Serial Monitor.

I am not sure where I am going wrong. I have got the phone app to connect and send data to the bluetooth module on an arduino101 but when connecting to the hm-10 with an arduino nano and sending data, nothing happens.

What is the name of Native app WebView alternative what can use any browser?

$
0
0

In React Native, there is WebView what can be used as fullscreen web browser for example for SSO auth.

But there is also another way, developers achieving same without usage of WebView. They seems to use default browser defined in OS to display SSO auth or some different web app.

The page is not fullscreen, there is readonly URL bar and three dots with settings + message Powered by <browser>

What is the name or how to make this? It seems to me as much better solution, because WebView not supporting everything and just using Chrome or other browser is much better.

view

Connecting bluetooth devices with React-Native App

$
0
0

I am using react-native-bluetooth-serial. I get this error whenever I try to connect a bluetooth device via my react native app:

Error: read failed, socket might closed or timeout, read ret: -1Unable to connect to device

Here's what I'm trying to do:

 connectToDevice () {    if (this.state.discovering) {      return false    } else {      this.setState({ discovering: true })      console.log("searching");      BluetoothSerial.list()      .then((Devices) => {        this.setState({ Devices, discovering: false })        for(var i = 0; 1; i++)        {          if(Devices[i]["name"] == "JBL Flip 3 SE")          {            console.log(Devices[i]["id"]);            BluetoothSerial.connect(Devices[i]["id"]).then((res) => {              console.log(res);            }).catch(err => {              console.log(err);            })            break;          }        }        // console.log(unpairedDevices);      })      .catch((err) => console.log(err.message))    }}

Same happens even when I clone the example repository.

Any idea why this is happening?

Firebase invalid credentials on Android

$
0
0

That's my concern, currently I'm developing an application that uses Firebase. Recently my identifiers for Android no longer work, the error tells me that the App ID does not match, however I am using google-services.json provides from my firebase console after adding my android application with its SHA key- 1.

My file is inside android/app folder like Firebase want it.

I have no problem with my iOS application, everything works fine.

Do you think I should try to delete Android ID clients OAuth 2.0 from google cloud platform and try to recreate it ?

I ran npx react-native run android and i got error

$
0
0

BUILD FAILED in 3m 0s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081Note: C:\Users\Olivia\Desktop\App1\android\app\src\debug\java\com\app1\ReactNativeFlipper.java uses or overrides a deprecated API.Note: Recompile with -Xlint:deprecation for details.

FAILURE: Build failed with an exception.

  • What went wrong:Execution failed for task ':app:installDebug'.

    com.android.builder.testing.api.DeviceException: com.android.ddmlib.AdbCommandRejectedException: closed

  • 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 3m 0s

at makeError (C:\Users\Olivia\Desktop\App1\node_modules\execa\index.js:174:9)at C:\Users\Olivia\Desktop\App1\node_modules\execa\index.js:278:16at processTicksAndRejections (internal/process/task_queues.js:97:5)at async runOnAllDevices (C:\Users\Olivia\Desktop\App1\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:5)at async Command.handleAction (C:\Users\Olivia\Desktop\App1\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:186:9)

drawernavigation doesn't hide screen

$
0
0

I am using react-navigation 5 and I have stack navigation and inside drawer navigation, I want to hide some of the drawer's navigation screens. So, I pass null in drawerLabel attribute as follow

import * as React from 'react';import {createDrawerNavigator} from '@react-navigation/drawer';import ShowNotes from "../screens/notes/ShowNotes";const Drawer = createDrawerNavigator();const DrawerNavigation = () => {    return (<Drawer.Navigator><><Drawer.Screen                     name="Home"                     component={ShowNotes}                    options={{                        headerTitle: 'All Notes',                        drawerLabel: () => null                    }}                /></></Drawer.Navigator>   );}export default DrawerNavigation;

This DrawerNavigation is inside a StackNavigation like so

const Stack = createStackNavigator();const Navigation = ({auth}) => {return (<NavigationContainer theme={CustomTheme}><Stack.Navigator            screenOptions={({navigation}) => ({                headerLeft: () => (<Button                        onPress={() => navigation.dispatch(DrawerActions.openDrawer())}                        title="Info"                        color="#fff"                    />                ),            })}><Stack.Screen                            name="Home"                            component={DrawerNavigation}                        /><Stack.Screen                            name="AddNoteScreen"                            component={AddNote}                        /><Stack.Screen                            name="UpdateNoteScreen"                            component={UpdateNote}                        />            }</Stack.Navigator></NavigationContainer>);};const mapStateToProps = state => {    return {auth: state.auth};};export default connect(mapStateToProps, {})(Navigation);

What I see on my screen is the drawer doesn't contain my screen but an empty blank area which is clickable

enter image description here

How I can stop displaying a screen in drawer?

Cheers

React navigation not showing the right screen

$
0
0

I have created a navigation setup for my application that should start off with a welcome screen on the welcome screen you find two buttons, one for registering and the other for logging in.

When the user registers or logs in he get sent to other screens. I have created a stack navigator between the log in and register screen and put them in a loginFlow constant and another between the welcome screen and the loginFlow constant and the navigation between these screens works, but for some reason the welcome screen doesn't get shown first instead I get the sign up screen (register screen).

Why is that the case and how can i make the welcomeScreen get shown first

import React from "react";import { View } from "react-native";import WeclomeScreen from "./app/screens/WelcomeScreen";import MainScreen from "./app/screens/MainScreen";import AccountScreen from "./app/screens/AccountScreen";import { Provider as AuthProvider } from "./app/context/AuthContext";import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs";import SignupScreen from "./app/screens/SignupScreen";import { createAppContainer, createSwitchNavigator } from "react-navigation";import { createStackNavigator } from "react-navigation-stack";import ResultShowScreen from "./app/screens/ResultShowScreen";import ResolveAuthScreen from "./app/screens/ResolveAuthScreen";import SigninScreen from "./app/screens/SigninScreen";import ArticleSaveScreen from "./app/screens/ArticleSaveScreen";import { setNavigator } from "./app/navigationRef";const articleListFlow = createStackNavigator({  Main: MainScreen, // screen with diffrent articles categories  ResultsShow: ResultShowScreen, // article details screen});const loginFlow = createStackNavigator({  Signup: SignupScreen,  Signin: SigninScreen,});loginFlow.navigationOptions = () => {  return {    headerShown: false,  };};articleListFlow.navigationOptions = {  title: "News Feed",  tabBarIcon: ({ tintColor }) => (<View><Icon style={[{ color: tintColor }]} size={25} name={"ios-cart"} /></View>  ),  activeColor: "#ffffff",  inactiveColor: "#ebaabd",  barStyle: { backgroundColor: "#d13560" },};const switchNavigator = createSwitchNavigator({  ResolveAuth: ResolveAuthScreen,  MainloginFlow: createStackNavigator({    WelcomeScreen: WeclomeScreen,    loginFlow: loginFlow,  }),  mainFlow: createMaterialBottomTabNavigator(    {      articleListFlow: articleListFlow,      ArticleSave: ArticleSaveScreen, // we dont need this one      Account: AccountScreen,    },    {      activeColor: "#ffffff",      inactiveColor: "#bda1f7",      barStyle: { backgroundColor: "#6948f4" },    }  ),});const App = createAppContainer(switchNavigator);export default () => {  return (<AuthProvider><App        ref={(navigator) => {          setNavigator(navigator);        }}      /></AuthProvider>  );};

drawer-navigation doesn't hide screen

$
0
0

I am using react-navigation 5 and I have stack navigation and inside drawer navigation, I want to hide some of the drawer's navigation screens. So, I pass null in drawerLabel attribute as follow

import * as React from 'react';import {createDrawerNavigator} from '@react-navigation/drawer';import ShowNotes from "../screens/notes/ShowNotes";const Drawer = createDrawerNavigator();const DrawerNavigation = () => {    return (<Drawer.Navigator><><Drawer.Screen                     name="Home"                     component={ShowNotes}                    options={{                        headerTitle: 'All Notes',                        drawerLabel: () => null                    }}                /></></Drawer.Navigator>   );}export default DrawerNavigation;

This DrawerNavigation is inside a StackNavigation like so

const Stack = createStackNavigator();const Navigation = ({auth}) => {return (<NavigationContainer theme={CustomTheme}><Stack.Navigator            screenOptions={({navigation}) => ({                headerLeft: () => (<Button                        onPress={() => navigation.dispatch(DrawerActions.openDrawer())}                        title="Info"                        color="#fff"                    />                ),            })}><Stack.Screen                            name="Home"                            component={DrawerNavigation}                        /><Stack.Screen                            name="AddNoteScreen"                            component={AddNote}                        /><Stack.Screen                            name="UpdateNoteScreen"                            component={UpdateNote}                        />            }</Stack.Navigator></NavigationContainer>);};const mapStateToProps = state => {    return {auth: state.auth};};export default connect(mapStateToProps, {})(Navigation);

What I see on my screen is the drawer doesn't contain my screen but an empty blank area which is clickable

enter image description here

How I can stop displaying a screen in drawer?

Cheers

Type androidx.appcompat.resources.R$dimen is defined multiple times

$
0
0

We have a React Native app where after upgrading to Android Studio 3.6.1 and Gradle plugin 3.6.1 we are seeing this compilation error:

Type androidx.appcompat.resources.R$dimen is defined multiple times: /Users/andrew/Software/project/android/app/build/intermediates/project_dex_archive/productionRelease/out/androidx/appcompat/resources/R$dimen.dex, /Users/andrew/Software/project/android/app/build/intermediates/project_dex_archive/productionRelease/out/15bdf8225afad69777cd7f9bd328ab094900c8289014e0107b56c5c62099dfea_3.jar:classes.dex

Here are our dependencies:

"dependencies": {"@dblackker/cameraroll": "^1.3.4","@react-native-community/async-storage": "^1.7.1","@react-native-community/geolocation": "^2.0.2","@react-native-community/netinfo": "^4.4.0","@react-native-community/push-notification-ios": "^1.0.6","@react-native-firebase/analytics": "^6.2.0","@react-native-firebase/app": "^6.2.0","@react-native-firebase/crashlytics": "^6.2.0","@react-native-firebase/perf": "^6.2.0","appcenter": "^2.6.1","appcenter-analytics": "^2.6.1","appcenter-crashes": "^2.6.1","axios": "^0.18.0","clone": "^2.1.2","immutability-helper": "^2.8.1","lodash": "^4.17.14","memoize-one": "^5.1.1","moment": "^2.22.2","prop-types": "^15.7.2","react": "16.9.0","react-custom-validation": "^0.5.7","react-native": "0.61.5","react-native-add-calendar-event": "^3.0.0","react-native-app-intro-slider": "^3.0.0","react-native-appearance": "^0.3.1","react-native-camera": "^3.8.0","react-native-contacts": "^5.0.6","react-native-device-info": "^4.0.1","react-native-gesture-handler": "^1.4.1","react-native-heic-converter": "^1.3.0","react-native-image-crop-picker": "^0.26.1","react-native-image-resizer": "^1.0.1","react-native-inappbrowser-reborn": "^3.1.0","react-native-iphone-x-helper": "^1.2.1","react-native-keyboard-aware-scroll-view": "^0.7.4","react-native-linear-gradient": "^2.5.6","react-native-maps": "0.26.1","react-native-modal": "^7.0.2","react-native-modal-datetime-picker": "^7.6.1","react-native-parsed-text": "^0.0.21","react-native-permissions": "^2.0.9","react-native-push-notification": "^3.1.9","react-native-reanimated": "^1.3.0","react-native-section-list-get-item-layout": "^2.2.3","react-native-shadow": "^1.2.2","react-native-share": "^2.0.0","react-native-svg": "^9.12.0","react-native-svg-uri": "^1.2.3","react-native-tab-view": "^2.3.0","react-native-version-number": "^0.3.6","react-navigation": "3.12.0","react-navigation-tabs": "^2.1.2","react-redux": "^5.0.7","redux": "^4.0.4","redux-thunk": "^2.3.0","rn-fetch-blob": "^0.11.2","validator": "^10.8.0"  }

Can anyone help figure out what the issue is, and how could we debug this type of issue in the future? Thank you!

Expo only working on web and fails on Android with multiple issues

$
0
0

My project is mainly based on this boilerplate. To not get into trouble with the deployments later on, I'm using expo.

Now I'm just wondering why the deployment to Android is not working. When I deploy it to web it works great without any trouble. But doing expo android deploy gives me expo android log and this on the Android Emulator:

android emulator error

But the project structure is clean and that index.css is working properly

project structure

What is the difference between a Run in web and Run on android?

Also when I just remove that index.css for testing. Web still works but without styles. But on Android I now get another error on my used localstorage.

I know there is a difference between react-native and react-web. But I was thinking that expo is able to handle this. Maybe I was expecting too much from expo? So am I wrong with that and all is fine. And all I have to do is making it work on Android, like fixing the index.css issue and the localstorage? Or is there a smarter way to get my obviously react-web application to work on my Android device?

Viewing all 28460 articles
Browse latest View live


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