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

Execution failed for task ':app:transformClassesWithMultidexlistForDebug - react native

$
0
0

I got this error:

Parsing json file: /Users/****/Desktop/****/app/android/app/google-services.jsonFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.> com.android.build.api.transform.TransformException: Error while generating the main dex list.

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 *   entryFile: "index.android.js", * *   // 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 = [    entryFile: "index.js"]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 = falseandroid {    compileSdkVersion 27    buildToolsVersion "27.0.3"    defaultConfig {        applicationId "com.arflax.ghamsar"        minSdkVersion 19        targetSdkVersion 26        versionCode 32        versionName "2.0.2"        multiDexEnabled true        ndk {            abiFilters "armeabi-v7a", "x86"        }    }    splits {        abi {            reset()            enable enableSeparateBuildPerCPUArchitecture            universalApk false  // If true, also generate a universal APK            include "armeabi-v7a", "x86"        }    }    signingConfigs {        release {            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {                storeFile file(MYAPP_RELEASE_STORE_FILE)                storePassword MYAPP_RELEASE_STORE_PASSWORD                keyAlias MYAPP_RELEASE_KEY_ALIAS                keyPassword MYAPP_RELEASE_KEY_PASSWORD            }        }    }    buildTypes {        release {            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"            signingConfig signingConfigs.release        }    }    // 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:            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits            def versionCodes = ["armeabi-v7a":1, "x86":2]            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 {    compile project(':react-native-geolocation-service')    compile project(':react-native-webview')    compile project(':@segment/analytics-react-native')    compile project(':react-native-device-info')    compile project(':react-native-maps')    compile project(':react-native-geocoder')    compile project(':react-native-linear-gradient')    compile project(':react-native-firebase')    compile project(':react-native-svg')    compile project(':react-native-image-resizer')    compile project(':react-native-fs')    compile project(':react-native-document-picker')    compile project(':react-native-contacts')    compile project(':react-native-vector-icons')    compile fileTree(dir: "libs", include: ["*.jar"])    compile "com.android.support:appcompat-v7:23.0.1"    compile "com.facebook.react:react-native:+"  // From node_modules    implementation(name:'app-release', ext:'aar')  implementation "com.google.android.gms:play-services-base:15.0.1" ///<--this   implementation 'com.google.android.gms:play-services-maps:15.0.1'  implementation "com.google.firebase:firebase-core:16.0.3" //<-- this  implementation "com.google.firebase:firebase-messaging:17.3.0" /// <-- this  implementation 'me.leolin:ShortcutBadger:1.1.21@aar'  implementation project(':react-native-maps')  compile project(':react-native-geocoder')  //implementation project(':@react-native-mapbox-gl_maps')  //implementation project(':@mapbox-react-native-mapbox-gl')//   implementation project(':react-native-geolocation-service')  implementation(project(':react-native-geolocation-service')) {        exclude group: 'com.google.android.gms', module: 'play-services-location'    }    implementation 'com.google.android.gms:play-services-location:15.0.1'  implementation(project(':react-native-maps')){     exclude group: 'com.google.android.gms', module: 'play-services-base'     exclude group: 'com.google.android.gms', module: 'play-services-maps' }}// 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'}fileTree(dir: 'libs', include: '**/*.aar')    .each { File file ->        dependencies.add("compile", [            name: file.name.lastIndexOf('.').with { it != -1 ? file.name[0..<it] : file.name },             ext: 'aar'        ])    }apply plugin: 'com.google.gms.google-services'com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

I'm using RN:

"react-native": "0.55.4",

React Native broadcast and discover nearby devices

$
0
0

First off: This is more of a logical question than a code-specific question.

I am trying to create a view similar to the iOS AirDrop view where users can see other users. This means, every user needs to broadcast/advertise their custom username, which can be seen by all other nearby users that scan the area.

I have tried using react-native-ble-plx, since I read on the Apple developer forum that iPhones can act as BLE (bluetooth low energy) peripherals. (Also, I read that newer Android devices support this as well)

I've tried the following:

import ble, { BleManager, Characteristic } from 'react-native-ble-plx';// ...const bleManager = new BleManager();bleManager.startDeviceScan(null, null, async (e, d) => {    if (e) console.log(`BT Error: ${JSON.stringify(e)}`);    if (d && d.id && d.isConnectable) {        console.log(`Connecting to: ${d.id} ('${d.name}')...`);        const device = await d.connect();        const services = await device.services();        console.log('services: ', services.join(', '));        const characteristic = await device.writeCharacteristicWithResponseForService(BLE_SERVICE_UUID, BLE_SERVICE_UUID, '123');        console.log(`Characteristics: ${JSON.stringify(characteristic)}`);    }});

But I haven't found a way to broadcast a value which others can read, is that even possible with BLE?

I've also looked into beacons (specifically react-native-beacons-manager), but I'm not sure if that is what I want since an Android/iOS phone is not a 'beacon'..

So my question is: Are there technologies/libraries that allow broadcasting of a message (my custom username) which others can see? Ideally I want to communicate between them, like exchanging a token, but that's not a requirement.

I'd appreciate any help or pointings into the right direction here, thanks!

How can I run my android emulator in React native?

$
0
0

I am working on the react native project with using WebStorm IDE, but when I run my react-native-cli run-android this command, I am taking these errors.

Here is the error

*"C:\Program Files\nodejs\node.exe" C:\Users\Asus\AppData\Roaming\npm\node_modules\react-native-cli run-androidinfo Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.Jetifier found 960 file(s) to forward-jetify. Using 8 workers...info JS server already running.* daemon not running; starting now at tcp:5037* daemon started successfullyinfo Installing the app...Starting a Gradle Daemon, 2 incompatible and 1 stopped Daemons could not be reused, use --status for details

Task :app:generatePackageList Task :app:preBuild Task :app:preDebugBuild Task :app:checkDebugManifest UP-TO-DATE Task :app:generateDebugBuildConfig UP-TO-DATE Task :app:compileDebugAidl NO-SOURCE Task :app:compileDebugRenderscript NO-SOURCE Task :app:javaPreCompileDebug UP-TO-DATE Task :app:mainApkListPersistenceDebug UP-TO-DATE Task :app:bundleDebugJsAndAssets SKIPPED Task :app:generateDebugResValues UP-TO-DATE Task :app:generateDebugResources UP-TO-DATE Task :app:mergeDebugResources UP-TO-DATE Task :app:createDebugCompatibleScreenManifests UP-TO-DATE Task :app:processDebugManifest UP-TO-DATE Task :app:processDebugResources UP-TO-DATE Task :app:compileDebugJavaWithJavac FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.Use '--warning-mode all' to show the individual deprecation warnings.See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings11 actionable tasks: 2 executed, 9 up-to-date

FAILURE: Build failed with an exception.

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

    Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_251 contains a valid JDK installation.

  • 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

BU�LD FAILED in 17s

Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

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

    Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_251 contains a valid JDK installation.

  • 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

BU�LD FAILED in 17s

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

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.

Also, I have already Android studio and Android development environment. Likewise, when I use adb devicescommand in the terminal, I can see my emulator. But project is not running on the emulator because of this mistake:

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.

React Native - Animation only works after Toggle Inspect on Android

$
0
0

I'm quite new on React/React-Native environment and I'm facing some problems with Animations on Android.

I'm using a react animation to show a bottom Alert on errors and warnings.The problem is that the animation is working fine on iOS but only works on Android after I enable the "Toggle Inspector", if I don't enable it the animation doesn't work, on debugger I'm able to see that the component is on the React components structure.

I already tried workarounds as setting the Animated.Value to 0.01 and changing Animated.createAnimatedComponent to Animated.View.

The animation should occur after the state is changed and the visible property is set to TRUE, the change of the state is OK as I can see it working on the React Native Debbuger, and the slideIn/slideOut functions are being called by the useEffect hook.

I'm on version React 16.11.0 and React-Native 0.62.2

Here is the main part of the code:

export const Alert = withTheme(({ theme: { primary, textGray } }) => {  const translateValue = useRef(new Animated.Value(0)).current;  const dispatch = useDispatch();  const {    visible,    data: { type, message }  } = useSelector(({ notification }) => notification);  const slideIn = useCallback(() => {    Animated.timing(translateValue, {      toValue: 1,      duration: 1000,      useNativeDriver: true    }).start();  }, [translateValue]);  const slideOut = useCallback(() => {    Animated.timing(translateValue, {      toValue: 0,      duration: 1000,      useNativeDriver: true    }).start();  }, [translateValue]);  const handleClose = () => {    dispatch(hideNotification());  };  useEffect(() => {    if (visible) {      slideIn();    } else {      slideOut();    }  }, [visible, slideIn, slideOut]);  return (<Wrapper      style={{        transform: [          {            translateY: translateValue.interpolate({              inputRange: [0, 1],              outputRange: [300, 0]            })          }        ]      }}><Content><Icon name={icons[type]} size={20} color={primary} /><Message>{message}</Message></Content><Button        onPress={handleClose}        accessible        accessibilityRole="button"        accessibilityLabel="Fechar notificação"><Icon size={20} name="x" color={textGray} /></Button></Wrapper>  );});const Wrapper = Animated.createAnimatedComponent(styled.SafeAreaView`  width: 100%;  border-top-width: 1px;  border-top-color: ${({ theme: { border } }) => border};  background: ${({ theme: { background } }) => background};  z-index: 1;  position: absolute;  flex-direction: row;  justify-content: space-between;  align-items: center;  bottom: 0;  left: 0;`);

Keyboard doesn't show up on focus textInput - Android

$
0
0

I use react native to make my application.

At some point, when the user clicks on an image, I automatically open a modal with a textInput inside with the props "autofocus=true".So I want by default the keyboard to open to allow the user to write something.

However, on IOS everything works perfectly but on Android, the textInput is correctly focused (there is the bar blinking on it) but the keyboard doesn't open, I have to click on the textInput for the keyboard to decide to open !

I tried doing focus in the componentDidMount and this kind of thing, but nothing works, the android keyboard doesn't want to open automatically.

I use React-Navigation with React-Native-Screens. I saw that there were some problems with that and the keyboard not opening, but I tried the given solutions and nothing works either!

I hope someone will be able to help me to solve my problem.

Thanks

Viktor

Imprecise height and getItemLayout in react native Android

$
0
0

I'm using getItemLayout to improve the performance of my SectionList in React Native. I'm supposed to return the height of items, which is working, but I've noticed that the actual height of components can vary on Android:

enter image description here

This causes noticeable shifting when I scroll far down the list--seemingly because when it actually renders the list items the height differs from what I've returned from getItemLayout sometimes up to 1 dp.

Is there a more accurate way to implement getItemLayout so that there is no shifting after scrolling?

Pick multiple images in react native Expo with Imagepicker

$
0
0

It seems like Expo only supports imagepicker for selecting one image rather than multiple images. Is there any way to pick multiple images without ejecting expo or starting new react-native-init?

Always On display in React Native

$
0
0

Always-On Display or AOD is a feature available on certain Samsung smartphones. AOD allows you to customise your screen to show time, date, battery status, notifications, screen savers and more.How can i achieve AOD in react-native. What package and permissions will be use to Develop in react-native.


How to get overflow visible working on Android with React Native V0.61 and Expo

$
0
0

I'm using React Native 0.61 with Expo SDK 37 which should support overflow visible as stated in the docs (https://reactnative.dev/docs/image-style-props#overflow). Nevertheless I can't get this to work on Android. I know there were some issues to this topic, but they all seem to be closed and resolved on GitHub (https://github.com/facebook/react-native/issues/6802).So how can I get this to work? Or is there even another way to achieve this picture?

Here is a snap where you can see the different behaviors. It behaves like intended on iOS but it's clipping on Android.

https://snack.expo.io/3C9xHTkUp

Issue in pictures:

IOS

Android

Type com.google.android.gms.common.internal.zzf is referenced as an interface from `com.google.android.gms.internal.zzcku`

$
0
0

I am trying to get a React Native app I made to work on android. It is giving me an error when I build the project, however: it says that Type com.google.android.gms.common.internal.zzf is referenced as an interface from com.google.android.gms.internal.zzcku. (I had several other errors before this one, but those were resolved.)

Just in case, here is my Android Studio:

enter image description here

Here is my 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' }    }}

And here is my gradle.properties:

# Project-wide Gradle settings.# IDE (e.g. Android Studio) users:# Gradle settings configured through the IDE *will override*# any settings specified in this file.# For more details on how to configure your build environment visit# http://www.gradle.org/docs/current/userguide/build_environment.html# Specifies the JVM arguments used for the daemon process.# The setting is particularly useful for tweaking memory settings.# Default value: -Xmx10248m -XX:MaxPermSize=256m# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8# When configured, Gradle will run in incubating parallel mode.# This option should only be used with decoupled projects. More details, visit# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects# org.gradle.parallel=true# AndroidX package structure to make it clearer which packages are bundled with the# Android operating system, and which are packaged with your app's APK# https://developer.android.com/topic/libraries/support-library/androidx-rnandroid.useAndroidX=true# Automatically convert third-party libraries to use AndroidXandroid.enableJetifier=trueandroid.enableR8 = falseandroid.enableD8 = true# Version of flipper SDK to use with React NativeFLIPPER_VERSION=0.33.1

Thanks.

build Android app using Expo error 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 problem with "yarn android" (sdk location)

$
0
0

I am on windows 7 64 bit, aiming to set it up for app development.

Installed yarn, react-native-app (yarn global add create-react-native-app), expo (create Npm install --unsafe-perm -g expo-cli), created a project (create-react-native-app myreactproj), added local.properties file in C:\Users\TOTAL\myreactproj\android with a line sdk.dir=C:\Users\TOTAL\AppData\Local\Android\Sdk, and the address does point to the sdk folder containing platform-tools folder with ADB executable and all. Still, as I follow with yarn android --no-jetifier, I am getting an error message telling me to add the sdk.dir line to local.properties or to add environmental variable ANDROID_SDK_ROOT, which I also have done, setting this to C:\Users\TOTAL\AppData\Local\Android\Sdk both for 'user' and 'environmental'.

What shall I do? I attach the screenshotsenter image description hereenter image description here

I'm confused to choose between flutter, react native and iOS and Android [closed]

$
0
0

I have an app which I have to develop or get developed. I'm really confused between react native and flutter, which to choose and why. I already know that flutter is far better in performance than react native but it doesn't have a developer community and is immature. I want to know if its immature then in what sense. I have thought of another approach too. I can also hire an android and an iOS developer, I know the cost rises but it doesn't gives issues like react and flutter. Kindly guide me why should I choose react native or flutter or go separately with android and iOS, with reasons. Thanks!

Simple React App crashed after binding isolate process

$
0
0

I'm newbie to React Native, I have created the simple project: 1. Add a new Service named "IsolatedService" 2. Declare on Manifest

<service        android:name=".IsolatedService"        android:enabled="true"        android:isolatedProcess="true"        android:exported="false"        android:process=":vkey"        android:directBootAware="true"        />

3. Bind it's to activity

@Overrideprotected void onStart() {    super.onStart();    this.bindService(intent, mIsolatedServiceConnection, BIND_AUTO_CREATE);}

4. App got crashed with below exception:

2020-05-25 17:47:55.658 27497-27497/com.test.process_v:test:com.myfirstproject.IsolatedService E/AndroidRuntime: FATAL EXCEPTION: mainProcess: com.test.process_v:test:com.myfirstproject.IsolatedService, PID: 27497java.lang.RuntimeException: Unable to create application com.myfirstproject.MainApplication: java.lang.RuntimeException: java.io.IOException: cannot mkdir: /data/user/0/com.test.process_v/lib-main    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6465)    at java.lang.reflect.Method.invoke(Native Method)    at com.swift.sandhook.SandHook.callOriginMethod(SandHook.java:185)    at com.swift.sandhook.xposedcompat.hookstub.HookStubManager.hookBridge(HookStubManager.java:375)    at SandHookerNew_5sm3dthec8858ee0to4kj3c1ge.hook(Unknown Source:51)    at android.app.ActivityThread.access$1300(ActivityThread.java:219)    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1859)    at android.os.Handler.dispatchMessage(Handler.java:107)    at android.os.Looper.loop(Looper.java:214)    at android.app.ActivityThread.main(ActivityThread.java:7356)    at java.lang.reflect.Method.invoke(Native Method)    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) Caused by: java.lang.RuntimeException: java.io.IOException: cannot mkdir: /data/user/0/com.test.process_v/lib-main    at com.facebook.soloader.SoLoader.init(SoLoader.java:209)    at com.myfirstproject.MainApplication.onCreate(MainApplication.java:50)    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1189)    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6460)    at java.lang.reflect.Method.invoke(Native Method)     at com.swift.sandhook.SandHook.callOriginMethod(SandHook.java:185)     at com.swift.sandhook.xposedcompat.hookstub.HookStubManager.hookBridge(HookStubManager.java:375)     at SandHookerNew_5sm3dthec8858ee0to4kj3c1ge.hook(Unknown Source:51)     at android.app.ActivityThread.access$1300(ActivityThread.java:219)     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1859)     at android.os.Handler.dispatchMessage(Handler.java:107)     at android.os.Looper.loop(Looper.java:214)     at android.app.ActivityThread.main(ActivityThread.java:7356)     at java.lang.reflect.Method.invoke(Native Method)     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)  Caused by: java.io.IOException: cannot mkdir: /data/user/0/com.test.process_v/lib-main    at com.facebook.soloader.SysUtil.mkdirOrThrow(SysUtil.java:189)    at com.facebook.soloader.UnpackingSoSource.prepare(UnpackingSoSource.java:409)    at com.facebook.soloader.SoLoader.initSoSources(SoLoader.java:317)    at com.facebook.soloader.SoLoader.init(SoLoader.java:195)    at com.facebook.soloader.SoLoader.init(SoLoader.java:177)    at com.facebook.soloader.SoLoader.init(SoLoader.java:207)    at com.myfirstproject.MainApplication.onCreate(MainApplication.java:50)     at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1189)     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6460)     at java.lang.reflect.Method.invoke(Native Method)     at com.swift.sandhook.SandHook.callOriginMethod(SandHook.java:185)     at com.swift.sandhook.xposedcompat.hookstub.HookStubManager.hookBridge(HookStubManager.java:375)     at SandHookerNew_5sm3dthec8858ee0to4kj3c1ge.hook(Unknown Source:51)     at android.app.ActivityThread.access$1300(ActivityThread.java:219)     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1859)     at android.os.Handler.dispatchMessage(Handler.java:107)     at android.os.Looper.loop(Looper.java:214)     at android.app.ActivityThread.main(ActivityThread.java:7356)     at java.lang.reflect.Method.invoke(Native Method)     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 

App has crashed after isolate service got bound.Does anyone have any idea what it could be?

Expo - LocationTaskService.java NullPointerException on Intent.getExtras()

$
0
0

Creating an Expo app and have it run a sticky notification, results in a NullPointerException after 15-60 minutes.

Here is the RN code

//backgroundTasks.jsimport {Permissions} from 'react-native-unimodules';import * as Location from 'expo-location';import * as TaskManager from "expo-task-manager";import {getStore} from "../redux/configureStore";import {newLocation} from "../redux/actions/device";import {Log} from "./log";import {Colors} from "./style/colors";import * as db from '../utils/db';import {getTranslator, secondsToInterval} from "./functions";import {showAlert} from "../redux/actions/app";import {APP} from "../redux/constants/app";import {setIgnoreState} from "./state";export const BG_TRACKING = 'BG_TRACKING';Log.info(`Unregister all tasks`);TaskManager.unregisterAllTasksAsync().then(() => {    Log.info(`Defined new background task ${BG_TRACKING}`);    TaskManager.defineTask(BG_TRACKING, async ({ data: { locations }, error }) => {        if(error) {            Log.error('Error received for locations', error);        } else {            locations.forEach(l => getStore().dispatch(newLocation(l)));        }    });});export const unregister = async () => {    if(await Location.hasStartedLocationUpdatesAsync(BG_TRACKING)) {        await Location.stopLocationUpdatesAsync(BG_TRACKING);    }};let permissionIndicationOpen = false;export const register = async () => {    let user = getStore().getState().get(APP).get('currentUser');    if(!user) return;    let permissionState = await Permissions.getAsync(Permissions.LOCATION);    if(!permissionState.granted || permissionState.canAskAgain) {        if(permissionIndicationOpen) return;        permissionIndicationOpen = true;        setIgnoreState(true);        permissionState = await Permissions.askAsync(Permissions.LOCATION);        setIgnoreState(false);        if(permissionState.granted) {            permissionIndicationOpen = false;        } else {            const t = await getTranslator();            getStore().dispatch(showAlert(t('needPermission'), t('locationPermissionNeeded'), {                onConfirm: () => {                    permissionIndicationOpen = false;                    register()                }            }));        }    }    const start = async () => {        const t = await getTranslator();        try {            Log.info(`Registering background task ${BG_TRACKING}`);            let trackingInterval = await db.getValue('trackingInterval');            if (!trackingInterval) return;            let interval = +trackingInterval;            if (interval < 0) interval = 60 * 60 //every hour, but it will be ignored by the server;            await unregister();            await Location.startLocationUpdatesAsync(BG_TRACKING, {                accuracy: Location.Accuracy.Highest,                timeInterval: interval * 1000,                foregroundService: {                    notificationBody: +trackingInterval > 0 ? t('yourPositionIsBeingMonitored', {                        period: secondsToInterval(t, interval)                    }) : t('positionSentOnlyOnAlarm'),                    notificationColor: Colors.primary                }            });            Log.info(`Successfully registered background task ${BG_TRACKING}`);        } catch (e) {            Log.error(`Failed registering background task ${BG_TRACKING}`);            Log.error(e);        }    };    await start();};

This file is called in the index.js, the entry point.

Then I see this stacktrace in Crashlytics.

Fatal Exception: java.lang.RuntimeException: Unable to start service expo.modules.location.services.LocationTaskService@97ff6c3 with null: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4222)       at android.app.ActivityThread.access$2100(ActivityThread.java:231)       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1984)       at android.os.Handler.dispatchMessage(Handler.java:107)       at android.os.Looper.loop(Looper.java:214)       at android.app.ActivityThread.main(ActivityThread.java:7682)       at java.lang.reflect.Method.invoke(Method.java)       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Download manager could not resolve downloaded file path

$
0
0

I'm using rn-fetch-blob to download file pdf although the file downloaded in download manager on android but it throw and return error: "Download manager could not resolve downloaded file path"

export const checkPermissionToDownload = async url => {  //Function to check the platform  //If iOS the start downloading  //If Android then ask for runtime permission  if (typeof url !== 'string') {    return Alert.alert('Liên kết không hợp lệ');  }  if (Platform.OS === 'ios') {    downloadPDF(url);  } else {    try {      const granted = await PermissionsAndroid.request(        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,        {          title: 'Storage Permission Required',          message: 'This app needs access to your storage to download Photos',        },      );      if (granted === PermissionsAndroid.RESULTS.GRANTED) {        //Once user grant the permission start downloading        console.log('Storage Permission Granted.');        downloadPDF(url);      } else {        //If permission denied then show alert 'Storage Permission Not Granted'        alert('Storage Permission Not Granted');      }    } catch (err) {      console.log('checkPermissionToDownload -> err', err);      //To handle permission related issue      console.warn(err);    }  }};export const downloadPDF = fileUrl => {  try {    const {      dirs: { DownloadDir, DocumentDir },    } = RNFetchBlob.fs;    const isIOS = Platform.OS === 'ios';    const aPath = Platform.select({ ios: DocumentDir, android: DownloadDir });    const date = new Date();    const file_name = Math.floor(date.getTime() + date.getSeconds() / 2);    const fPath = `${aPath}/${file_name}.pdf`;    const configOptions = Platform.select({      ios: {        fileCache: true,        path: fPath,        appendExt: 'pdf',      },      android: {        fileCache: false,        appendExt: 'pdf',        addAndroidDownloads: {          useDownloadManager: true,          title: `${file_name}.pdf`,          description: 'Downloading...',          mime: 'application/pdf',          mediaScannable: true,          notification: true,        },      },    });    if (isIOS) {      // This iOS block works fine..      RNFetchBlob.config(configOptions)        .fetch('GET', fileUrl)        .then(async resp => {          // This options is for file sharing in iOS. Works fine.          const options = {            title: 'Receipt File', // type: 'pdf',            urls: [`file://${fPath}`],          };          await Share.open(options);          await RNFS.unlink(fPath);        })        .catch(error => {          console.log('error', error);        });      return;    }    // Android Part.  Not working as expected.    RNFetchBlob.config(configOptions)      .fetch('GET', fileUrl) // This line downloads file.      .then(resp => {        console.log('resp', resp);        RNFetchBlob.android.actionViewIntent(res.path(), 'application/pdf');        // This alert pops up. But, rest.path is empty string, not undefined nor null.        Alert.alert('Success', resp.path());      })      .catch(e => {        // Failure callback registration        console.log('downloadPDF -> e', e);        Alert.alert('Tải file không thành công');      });  } catch (error) {    console.log('shareContent -> error', error);  }};checkPermissionToDownload('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf')

I found the issue still available. https://github.com/joltup/rn-fetch-blob/issues/214Everyone have solution for that?

React Native Send sms within the app

$
0
0

I want to send sms to multiple numbers without opening to default messaging app.I try to use react-native-sms-x but its not maintained and my project just stuck at compiling.Also I used react-native-sms but it open default Messaging App filled with one user number and message body and had to click send button of it too.

react-native link ios to android migration

$
0
0

I am looking to migrate an existing react-native iOS app (with quite a lot of dependencies) to android and none/few of the react-native link commands have been executed in the context of android,

  1. Is there either a way to link all?
  2. Or, any tools that can take the iOS ios/Podfile file and generate the android equivalent from it?

Linking.getInitialURL() is not being cleared after used for deeplink

$
0
0

I've had this problem for like 2 weeks. I used Wix's Navigation for navigating around the app. I followed this tutorial for implementing the deeplink/universal link.

I have a base class called BaseScreen where I keep all the deeplink handler like in the tutorial. This BaseScreen would looks like this:

componentDidMount(){    // this handles the case where the app is closed and is launched via Universal Linking.    Linking.getInitialURL()        .then((url) => {          if (url) {            // Alert.alert('GET INIT URL','initial url  '+ url)            this.resetStackToProperRoute(url)          }        })        .catch((e) => {})   // This listener handles the case where the app is woken up from the Universal or Deep Linking   Linking.addEventListener('url', this.appWokeUp);  }  componentWillUnmount(){    // Remove the listener    Linking.removeEventListener('url', this.appWokeUp);  }  appWokeUp = (event) => {    // this handles the use case where the app is running in the background and is activated by the listener...    // Alert.alert('Linking Listener','url  '+ event.url)    this.resetStackToProperRoute(event.url)  }  resetStackToProperRoute = (url) => {    // grab the trailing portion of the url so we can use that data to fetch proper information from the server    let trailing = url.slice(url.lastIndexOf('=') + 1, url.length)    // go to the desired screen with the trailing token grabbed from the url    this.props.navigator.resetTo({      screen: 'NewPassword',      overrideBackPress: true,      passProps: {        token: trailing      },      animated: true,      animationType: 'fade',      navigatorStyle: {      navBarHidden: true,  }})  }

When the app launch, it'll show the screen LoginScreen which extends the BaseScreen above. After killing the app, click the url from the mail, the app launches LoginScreen first, then it'll redirect to the screen NewPassword, and after everything has done, I'll redirect back to LoginScreen by:

this.props.navigator.resetTo({  screen: 'LoginScreen',  animated: true,  overrideBackPress: true,  animationType: 'fade',  navigatorStyle: {    navBarHidden: true,  }})

But the Linking.getInitialURL() of the LoginScreen still receive the old url, so it'll redirect to NewPassword again, and it's a loop.

I've also tried to pass: passProps: {} option when resetTo the LoginScreen but no luck.

I guess the only way to fix it is to clear the initialUrl manually after everything's done in NewPassword screen. The listener for the BaseScreen should be there because if I don't kill the app (just minimize it), the listener should be running to navigate to NewPassword.

Wix's navigation has a doc for Deeplink, I tried putting method onNavigatorEvent(event) into the BaseScreen but it doesn't get called. I don't know if I miss something.

Thank you for your time. Any idea would be appreciated

How to restrict a url in react-native

$
0
0

I am making an app in RN.

I just signed up for Mapbox and it says make your token more secure by adding url restrictions.

How can we have url restrictions for app? (or can we even have?)

enter image description here

Viewing all 28457 articles
Browse latest View live


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