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

Intent.getData() is returing null in Android. react-native

$
0
0

I am working on a dialer app using react-native and want to give my app option to open any phone number. So I added this to my manifest file.

<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter><intent-filter><action android:name="android.intent.action.DIAL" /><category android:name="android.intent.category.DEFAULT" /></intent-filter><intent-filter><action android:name="android.intent.action.CALL_BUTTON" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /></intent-filter><intent-filter><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:mimeType="vnd.android.cursor.dir/calls" /></intent-filter><intent-filter><action android:name="android.intent.action.VIEW" /><action android:name="android.intent.action.DIAL" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:scheme="tel" /></intent-filter>

and I am trying to access the phone number and then pass it to the react component as props. but the phone number value is only received when the app starts and I want the phone number whenever the user clicks on any phone number.

@Overrideprotected void onStart(){    super.onStart();    Intent intent = getIntent();    if(intent.getData() != null){        Toast.makeText(getApplicationContext(), intent.getData().toString(),     Toast.LENGTH_SHORT).show();     } else{        Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_SHORT).show();    }}

ReactNative Metro Bundler not starting automatically

$
0
0

react-native run-android not starting bundler so i triedreact-native start it showing below error.

┌──────────────────────────────────────────────────────────────────────────────┐│││  Running Metro Bundler on port 8081.                                         ││││  Keep Metro running while developing on any JS projects. Feel free to        ││  close this tab and run your own Metro instance if you prefer.               ││││  https://github.com/facebook/react-native                                    │││└──────────────────────────────────────────────────────────────────────────────┘events.js:167      throw er; // Unhandled 'error' event      ^Error: listen EADDRINUSE :::8081    at Server.setupListenHandle [as _listen2] (net.js:1286:14)    at listenInCluster (net.js:1334:12)    at Server.listen (net.js:1421:7)    at /Users/user/Documents/Prasanth/AwesomeProject/node_modules/metro/src/index.js:157:18    at new Promise (<anonymous>)    at Object.<anonymous> (/Users/user/Documents/Prasanth/AwesomeProject/node_modules/metro/src/index.js:156:12)    at Generator.next (<anonymous>)    at step (/Users/user/Documents/Prasanth/AwesomeProject/node_modules/metro/src/index.js:47:262)    at /Users/user/Documents/Prasanth/AwesomeProject/node_modules/metro/src/index.js:47:422Emitted 'error' event at:    at Server.WebSocketServer._onServerError (/Users/user/Documents/Prasanth/AwesomeProject/node_modules/ws/lib/WebSocketServer.js:82:50)    at Server.emit (events.js:187:15)    at emitErrorNT (net.js:1313:8)    at process._tickCallback (internal/process/next_tick.js:63:19)

react-native info

  React Native Environment Info:    System:      OS: macOS High Sierra 10.13.6      CPU: x64 Intel(R) Core(TM)2 Duo CPU     E7600  @ 3.06GHz      Memory: 3.36 GB / 12.00 GB      Shell: 3.2.57 - /bin/bash    Binaries:      Node: 10.12.0 - /usr/local/bin/node      Yarn: 1.10.1 - /usr/local/bin/yarn      npm: 6.4.1 - /usr/local/bin/npm      Watchman: 4.9.0 - /usr/local/bin/watchman    SDKs:      iOS SDK:        Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0      Android SDK:        Build Tools: 21.1.2, 23.0.1, 25.0.0, 26.0.0, 26.0.1, 26.0.2, 26.0.3, 27.0.3, 28.0.2, 28.0.3        API Levels: 21, 22, 23, 24, 25, 26, 27    IDEs:      Android Studio: 3.2 AI-181.5540.7.32.5056338      Xcode: 10.0/10A255 - /usr/bin/xcodebuild    npmPackages:      react: 16.5.0 => 16.5.0       react-native: 0.57.2 => 0.57.2     npmGlobalPackages:      react-native-cli: 2.0.1      react-native-git-upgrade: 0.2.7

package.json

{"name": "AwesomeProject","version": "0.0.1","private": true,"scripts": {"start": "node node_modules/react-native/local-cli/cli.js start","test": "jest"  },"dependencies": {"react": "16.5.0","react-native": "0.57.2"  },"devDependencies": {"babel-jest": "23.6.0","jest": "23.6.0","react-test-renderer": "16.5.0"  },"jest": {"preset": "react-native"  }}

I tried cleaning cache and reverse adb still am getting that issue

react-native run-android showing below error.

enter image description here

Android Home configuration

export ANDROID_HOME=/<Path>/android-sdk-macosxexport PATH=$PATH:$ANDROID_HOME/toolsexport PATH=$PATH:$ANDROID_HOME/tools/binexport PATH=$PATH:$ANDROID_HOME/platform-toolsexport PATH=$PATH:$ANDROID_HOME/emulator

How to resolve this issue.

How to target api level 29 in expo [duplicate]

$
0
0

I am trying to publish my react native app on play store but whenever i try to upload my apk it throws an error which says

Your app currently targets API level 28 and must target at least API level 29 to ensure that it is build on the latest APIs optimised for security and performance.

Here is my app.json

{"expo": {"name": "Sanjivani","slug": "sanjivani","version": "1.0.0","sdkVersion": "38.0.0","orientation": "portrait","icon": "./assets/new.png","android": {"package": "com.autosaft.newapp","versionCode": 1,"icon": "./assets/new.png"    },"splash": {"image": "./assets/splash.png","resizeMode": "contain","backgroundColor": "#ffffff"    },"updates": {"fallbackToCacheTimeout": 0    },"assetBundlePatterns": ["**/*"    ],"ios": {"supportsTablet": true    },"web": {"favicon": "./assets/favicon.png"    }  }}

Does anyone knows what should i do?

How to set Surface to TvView?

$
0
0

Is there any possibility, to set your own SurfaceView for TvView?

TvView dont have any method like setDisplay or onSurfaceCreated.

We have a system where every player has own surface and now we trying to implement a new player (provided by customer) which can play live encrypted multicast. Customer provided us TvView, on which I call tune when I want to play something. I build player logic on top of TvView, but I cant integrate it to our system, because we have our own SurfaceView, which can react on react-native events (rise on top and hide).

Is there any possibility to say TvView that is should use custom SurfaceView?

why do i have to reload the app after change direction from LTR to RTL in react-native?

$
0
0

I use I18nManager.forceRTL(true) in initialState or componentDidMount life cycle but it does't work and if I reload my App, it works.

I mean I have to reload the App to see the effect, what is the reason?

Thanks in advance

gradlew assembleRelease doesn't work with react-native-camera

$
0
0

I can't build release version of application. When I write .\gradlew assembleRelease, I get this error Execution failed for task ':react-native-camera:compileGeneralReleaseJavaWithJavac'. My app/build.gradle file:

apply plugin: "com.android.application"apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"import com.android.build.OutputFileproject.ext.react = [    entryFile: "index.js",    enableHermes: false,  // clean and rebuild if changing]apply from: "../../node_modules/react-native/react.gradle"def enableSeparateBuildPerCPUArchitecture = falsedef enableProguardInReleaseBuilds = falsedef jscFlavor = 'org.webkit:android-jsc:+'def enableHermes = project.ext.react.get("enableHermes", false);android {    compileSdkVersion rootProject.ext.compileSdkVersion    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    defaultConfig {        applicationId "com.ms.showcase"        minSdkVersion rootProject.ext.minSdkVersion        targetSdkVersion rootProject.ext.targetSdkVersion        versionCode 200        versionName "2.0.0"        multiDexEnabled true        missingDimensionStrategy "react-native-camera", "general"    }    splits {        abi {            reset()            enable enableSeparateBuildPerCPUArchitecture            universalApk false  // If true, also generate a universal APK            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"        }    }    signingConfigs {        debug {            storeFile file('debug.keystore')            storePassword 'android'            keyAlias 'androiddebugkey'            keyPassword 'android'        }    }    buildTypes {        debug {            signingConfig signingConfigs.debug        }        release {            // Caution! In production, you need to generate your own keystore file.            // see https://facebook.github.io/react-native/docs/signed-apk-android.            signingConfig signingConfigs.debug            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"        }    }    // applicationVariants are e.g. debug, release    applicationVariants.all { variant ->        variant.outputs.each { output ->            // For each separate APK per architecture, set a unique version code as described here:            // https://developer.android.com/studio/build/configure-apk-splits.html            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]            def abi = output.getFilter(OutputFile.ABI)            if (abi != null) {  // null for the universal-debug, universal-release variants                output.versionCodeOverride =                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode            }        }    }}dependencies {    // This should be here already    // Firebase dependencies    implementation "com.google.android.gms:play-services-base:16.1.0"    implementation "com.google.firebase:firebase-core:16.0.9"    implementation "com.google.firebase:firebase-messaging:19.0.0"    implementation 'me.leolin:ShortcutBadger:1.1.21@aar'    implementation fileTree(dir: "libs", include: ["*.jar"])    implementation "com.facebook.react:react-native:+"  // From node_modules    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'    if (enableHermes) {        def hermesPath = "../../node_modules/hermes-engine/android/";        debugImplementation files(hermesPath +"hermes-debug.aar")        releaseImplementation files(hermesPath +"hermes-release.aar")    } else {        implementation jscFlavor    }}// Run this once to be able to run the application with BUCK// puts all compile dependencies into folder libs for BUCK to usetask copyDownloadableDepsToLibs(type: Copy) {    from configurations.compile    into 'libs'}apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)apply plugin: 'com.google.gms.google-services'

I tried to search in Google, but I found nothing. My RN version 0.61. I know that it can be a problem with AndroidX, and downgrade to RN 0.59 can help, but I think, that it's not a good idea.

How can I fix this this problem?

React Native Android BackHandler Exit App

$
0
0

I want to implement the BackHandler to run on one component and keep the default behavior of the hardware back button 'go to the previous screen' in the rest of my app, I have a component named 'cases.js' I want to exit the app if the user clicked the back button while this component is in the screen and to navigate back if the user is on any other component, the cases screen lays over the Login screen.

Here is what I've tried in 'cases.js' file:

  componentDidMount = async () => {    await BackHandler.addEventListener('hardwareBackPress', this._closeApp())  }  componentWillUnmount = async () => {    await BackHandler.removeEventListener('hardwareBackPress', this_closeApp());  }  _closeApp = async () => {    BackHandler.exitApp();  }

but it keeps closing the app immediately.

How may I achieve that?

How to reduce Android APK size in react-native?

$
0
0

I am working on react native project , but whenever i am building an Apk file , it give me Apk of 47MB.I tried every documentation which i found useful on google but nothing works for me, Is there any way to reduce my App size below 10MB as the app only contain three or four pages. Any help would be appreciated


React Native Issue while setting up new Project macOs

$
0
0

$ react-native run-androidinfo Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.Jetifier found 967 file(s) to forward-jetify. Using 4 workers...info JS server already running.info Installing the app...

FAILURE: Build failed with an exception.

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

  • Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

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

BUILD FAILED in 669ms

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 app:installDebug -PreactNativeDevServerPort=8081

But it was running perfectly on ios simulator only problem while running or android emulator

Clear install for apk in Expo

$
0
0

So, I had a weird question: I make just the APK from a app for android in Expo, and the app is avaliable online on the Google Play, I've tested and then I uninstall from my phone, so has some cache. The problem is that when I install the apk with my modifications generated on Expo, they don't show and the app not update, even if I change the version.Is there a way to erase it after install (check if has some cache and erase), or is other type of solution? I've tested in a phone that never install the app, and has my modifications.Thanks!

Network error: the network request failed on some phone brand and POST type requests

$
0
0

DescriptionHello

Our application is in production and has problems for POST type requests. On some phone brands and all android versions (5, 6, 7,8,9,10). and on the other hand the Post type requests work very well on other phones and all android version (5,6,7,8,9,10)

The exact error produced is: Error · Error: Network error: Network request failed.

React native command result:

Different solutions already tested:

By default, access to our backend is via https using cloudflare. I even thought that it could be an https certificate problem, I changed cloudflare to use a certificate fromLet's Encryptletsencrypt, until then we have the same problem.We figured this was a problem with the https protocol and decided on http and added to AndroidManifest.xml the directive:

<android application: usesCleartextTraffic = "true"></application>

despite all this we have the same problem namely the POST type request are not functional on some brands of phone and any android version (5,6,7,8,9,10)

React Native version:System:    OS: Linux 4.19 Debian GNU/Linux 10 (buster) 10 (buster)    CPU: (4) x64 Intel(R) Core(TM) i3-5005U CPU @ 2.00GHz    Memory: 761.15 MB / 11.65 GB    Shell: 5.0.3 - /bin/bash  Binaries:    Node: 10.15.2 - /usr/bin/node    Yarn: 1.17.3 - /usr/bin/yarn    npm: 6.14.5 - /usr/bin/npm  IDEs:    Android Studio: 4.0 AI-193.6911.18.40.6514223  npmPackages:    react: 16.9.0 => 16.9.0     react-native: 0.61.5 => 0.61.5   npmGlobalPackages:    react-native-cli: 2.0.1    react-native-rename: 2.4.1

Thank you for any help in relation to this problem because at this time we already no longer block more than 1200 Registrations on our Mobile application.

React native Android - Authenticate using lock screen credentials like PIN, pattern, or password for non Biometric devices

$
0
0

I am working on a React Native Android app to implement authentication. Implementing Biometric authentication is not bad, but since a lot of Android devices still don't support biometrics, we have to implement secure sign in for them as well.

So, one of the requirements is to authenticate into the app using lock screen credentials like PIN, pattern, or password for devices that don't support Biometrics.

This is how its done in Native android in Java/Kotlin, but I haven't been able to find out how to do it natively using React Native.

Anyone have clues or suggestions, I would greatly appreciate it!

How to store and update steps count data with Date wise in firebase

$
0
0

I'm working on step counting app.I want to store user data userGoal, userSteps day wise and i want to update that data dynamically in Firebase Firestore.

I created array of object to store and update users every day data, I search about it but showing we can't update data with specific index from the array in Firestore.

Any other way to store and update users every day data with Date. ???

this i created firestore structure array of object:

this i created firestore structure array of object

TypeError: cb.apply is not a function

$
0
0

I'm trying to run an existing React Native project that uses Metro Bundler. My operating system is Ubuntu 20.04 and I've tried to run the app both on physical Android device and on an Android simulator that I created with Android Studio.

I have successfully cloned the project's repo, installed its dependencies (yarn), built the app (react-native run-android), and opened the app on my phone or simulator. However, running react-native start errors out saying TypeError: cb.apply is not a function. Here is the full information and errors I get when running react-native start:

$ react-native startwarn Your project is using deprecated "rnpm" config that will stop working from next release. Please use a "react-native.config.js" file to configure the React Native CLI. Migration guide: https://github.com/react-native-community/cli/blob/master/docs/configuration.mdwarn The following packages use deprecated "rnpm" config that will stop working from next release:  - rn-fetch-blob: https://npmjs.com/package/rn-fetch-blobPlease notify their maintainers about it. You can find more details at https://github.com/react-native-community/cli/blob/master/docs/configuration.md#migration-guide.┌──────────────────────────────────────────────────────────────────────────────┐│││  Running Metro Bundler on port 8081.                                         ││││  Keep Metro running while developing on any JS projects. Feel free to        ││  close this tab and run your own Metro instance if you prefer.               ││││  https://github.com/facebook/react-native                                    │││└──────────────────────────────────────────────────────────────────────────────┘warn Your project is using deprecated "rnpm" config that will stop working from next release. Please use a "react-native.config.js" file to configure the React Native CLI. Migration guide: https://github.com/react-native-community/cli/blob/master/docs/configuration.mdwarn The following packages use deprecated "rnpm" config that will stop working from next release:  - rn-fetch-blob: https://npmjs.com/package/rn-fetch-blobPlease notify their maintainers about it. You can find more details at https://github.com/react-native-community/cli/blob/master/docs/configuration.md#migration-guide.Looking for JS files in   /home/ggiuffre/Documents/squib/app Loading dependency graph, done. BUNDLE  [android, dev] ./index.js ░░░░░░░░░░░░░░░░ 0.0% (0/1)/home/ggiuffre/Documents/squib/app/node_modules/@react-native-community/cli/node_modules/graceful-fs/polyfills.js:285        if (cb) cb.apply(this, arguments)                   ^TypeError: cb.apply is not a function    at /home/ggiuffre/Documents/squib/app/node_modules/@react-native-community/cli/node_modules/graceful-fs/polyfills.js:285:20    at FSReqCallback.oncomplete (fs.js:169:5)

Installing graceful-fs (as recommended by another post about the same problem) doesn't change anything, and I still get the same error.

What could be the issue here? Thanks in advance.

How to resolve the build error on react-native?

$
0
0

I'm trying to make a build environment to make an android app but I haven't been able to succeed to build the project. The build log is as follows,

Starting Gradle Daemon...Gradle Daemon started in 5 s 673 ms:ReactNative:Running '[node, -e, console.log(require('react-native/cli').bin);]' command failed.FAILURE: Build failed with an exception.* Where:Script 'C:\WorkSpace\MyProject\node_modules\@react-native-community\cli-platform-android\native_modules.gradle' line: 179* What went wrong:A problem occurred evaluating script.> Cannot run program "node" (in directory "C:\WorkSpace\MyProject\android"): CreateProcess error=2, �w�肳�ꂽ�t�@�C����������܂���B

It looks exactly same as the link below and I did the same thing but I can't resolve the problem and the log that it makes is always the same.

https://forums.expo.io/t/android-cannot-run-program-node-error-2-no-such-file-or-directory/37693


Communication between multiple apps within same mobile device

$
0
0

I am working on implementing a feature where I will be having two different apps (i.e., appA and aapB) where appA is built on react-native(android/ios) and appB is built on Android native(java)/iOS native(Objective C).

I want the two apps to communicate within the same mobile device, if I make any changes on the react-native app, the same should replicate on native app as well or send some data to the other app so that I can handle the necessary changes.

RNCSlider was not found in the UI Manager when trying to use @react-native-community/slider

$
0
0

I'm trying to create a slider in my react native Android App, and relatively new to React Native. The React Native documentation says their Slider component is deprecated (https://reactnative.dev/docs/slider.html) and directs us to use @react-native-community/slider instead (https://github.com/react-native-community/react-native-slider/blob/master/README.md).

I installed the library in my project directory using npm install @react-native-community/slider --save.

The install succeeded and my versions in my package.json are as follows:

"dependencies": {"@react-native-community/slider": "^3.0.3","react": "16.13.1","react-native": "0.63.0" },

I am including the Slider in my source file with import Slider from '@react-native-community/slider';, however when ever I try to actually create a slider in my code with the <Slider> ... </Slider> tags, I get the following compile error:

ERROR Invariant Violation: requireNativeComponent: "RNCSlider" was not found in the UIManager.

I've been banging my head against the wall and can't figure out how to clear the error.I am on Windows 10 x64 developing for Android.Thanks in advance!

react native gesture handler is not working with modal in Android

$
0
0

I am having an issue in using PanGestureHandler from react-native-gesture-handler with Modal. This is perfectly working in iOS but not in android. And Moreover when I changed Modal in to View component it is working in Android as well. Please any one can suggest me a solution for this problem.

class Circle extends Component {  _touchX = new Animated.Value(windowWidth / 2 - circleRadius);  _onPanGestureEvent = Animated.event([{ nativeEvent: { x: this._touchX } }], { useNativeDriver: true });  render() {    return (<Modal        isVisible={true}><PanGestureHandler          onGestureEvent={this._onPanGestureEvent}><Animated.View style={{            height: 150,            justifyContent: 'center',          }}><Animated.View              style={[{                backgroundColor: '#42a5f5', borderRadius: circleRadius, height: circleRadius * 2, width: circleRadius * 2,              }, {                transform: [{ translateX: Animated.add(this._touchX, new Animated.Value(-circleRadius)) }]              }]}            /></Animated.View></PanGestureHandler></Modal>    );  }}

React-Native-Crop-Image doesn't work on android , How to crop images on android and it should be same for ios also

$
0
0

I have tried this library react-native-image-crop-picker as suggested on this stackoverflow answer

I have followed each and every step mentioned here

  1. Run npm i react-native-image-crop-picker@0.4.2
  2. import ImagePicker from 'react-native-image-crop-picker';then

ImagePicker.openPicker({width: 300,height: 400,cropping: true}).then(image => {console.log(image);});

Also in // file: android/settings.gradle have added the below code

include ':react-native-image-crop-picker'project(':react-native-image-crop-picker').projectDir = newFile(settingsDir,'../node_modules/react-native-image-crop-picker/android')

Also as mentioned in the documentation have added required code in build.gradle& MainActivity.java file

But this is not working for me on Android but working perfectly on iOS . On Android I have given to crop images by scale type only not as flexible crop.

Uploading Image to server in react native. Getting Error "Network request failed"

$
0
0

Calling function :This is where I am creating a API call.

onAddMenuApi(formData) {    return fetch(UserManagerIns.getUserData('API_URL') +'menu-item-add', {      method: 'POST',      headers: {        Accept: 'application/json','Content-Type': 'multipart/form-data',      },      body: formData,    })      .then(response => {        if (!response.ok) {          throw new Error(response.status);        }        return response.json();      })      .then(myres => {        console.log('Item Add API data::::: '+ JSON.stringify(myres));        return myres;      })      .catch(error => {        return error;      });  },

Setting Parameters :This is where I am make a API call after this and set a formData Parameter.

let params = {      title: this.state.title,      price: this.state.price,      menu_cat_id: this.state.menu_cat_id,    };    let formData = new FormData();    for (var k in params) {      formData.append(k, params[k]);      console.log('My Data :: '+ params[k]);    }    formData.append('image_url', {      uri: this.state.ImageSource,      name: this.state.filename,      type: this.state.type,    });

In response I am getting "Network request failed".

I have added in AndroidManifest file the line : android:usesCleartextTraffic="true"

I have added network_security_config.xml as well but it is not working.

<?xml version="1.0" encoding="utf-8"?><network-security-config><base-config cleartextTrafficPermitted="true"><trust-anchors><certificates src="system" /></trust-anchors></base-config></network-security-config>
Viewing all 29603 articles
Browse latest View live


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