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

Implement BouncingScrollPhysics animation in react native

$
0
0

How can I implement something like BouncingScrollPhysics that is one of ScrollPhysics type in flutter's listView in react native.

I know there is bounce property for react native, but it only works for iOS, I need for android too.

Here is What I want to implement in react native.

Example


React-native when running an android project throws an error (null is not an object)

$
0
0

When I run my react-native project in the android emulator. It brings up an error.

Error message:

TypeError : null is not an object (evuluating '_RNGestureHAndlerModule.default.Direction')

Error Message Screenshot

how can I solve this problem?

react naive - images begin to disappear after subsequent renders

$
0
0

On intial render the images are rendering fine, then after 4th render, the images begin to disappear untill there are none left. My gut feeling is probably because of me fetching the images in the react useLayoutEffect. The render then loop this featureList and sets the react native Image uri.

useLayoutEffect(() => {  const feat = [];  loginState.featureList.map((featureName, index) => {    const image = getFeatureImagePath(featureName);    const feature = {      featureName: featureName,      image: image,    };    feat.push(feature);  });  setFeatures(features.concat(feat));  showHeaderComponent();}, [showHeaderComponent, loginState.featureList]);

then on the render:

return (<View style={[globalStyles.container, styles.container]}><ScrollView indicatorStyle={'white'} showsVerticalScrollIndicator={true}><ImageBackground      source={require('test/app/images/icons/imageBackground.png')}      style={[globalStyles.backgroundImage]}      imageStyle={[globalStyles.backgroundImageInner]}><View style={styles.contentContainer}>        {features.map((feature, index) => {          if (feature.image) {            return (<View key={feature.featureName} style={styles.featureImage}><TouchableNativeFeedback                  onPress={fn => featureNavigate(feature.featureName)}><View style={styles.content}><Image                      source={feature.image.uri}                      style={styles.appLogo}                    /><Text style={styles.label}>{feature.image.label}</Text></View></TouchableNativeFeedback></View>            );          }        })}</View></ImageBackground></ScrollView></View>);

the getFeatureImagePath function( which is called in the useLayoutEffect hook) is getting the image uri using the require function as below

{  featureName: appPages.feature,  uri: require('test/app/images/icons/feature.png'),  label: 'Test Feature',},

FlexDirection Change Based on Orientation Change in React-Native

$
0
0

My Code:

import React, { PureComponent } from 'react'import { StyleSheet, View } from 'react-native'import {    isPortrait} from './Constants'export default class TwoVideoView extends PureComponent {    render() {        return (<View style={styles.conatiner}><View style={[styles.videoHalfView, {backgroundColor: 'white'}]}></View><View style={[styles.videoHalfView, {backgroundColor: 'gray'}]}></View></View>        )    }}const styles = StyleSheet.create({    conatiner: {        flex: 1,        backgroundColor: 'red',        flexDirection: isPortrait ? ('column') : ('row')    },    videoFullView: {        width: '100%',        height: '100%'    },    videoHalfView: {        width: isPortrait ? ('100%') : ('50%'),        height: isPortrait ? ('50%') : ('100%')    }})

Portrait output:

enter image description here

Landscape Output:enter image description here

Expected Output:enter image description here

Can you please help what should I do to get this done?

I tried adding Dimensions.addListener('change') didn't workedI just want to update My View rendering not the other Api Stuff.

I need to change flexDirection: isPortrait ? ('column') : ('row')

export const isPortrait = () => {    const dim = Dimensions.get('screen');    return dim.height >= dim.width;  };

how to get picker of react native with fetch mysql

how to put delay between animations in Loop

$
0
0

Im using loop to run animation infinitely but i want to run animation with a delay each time. the delay inside the animation just runs in the first time and not for further animation running.

Code:

Animated.loop(            Animated.timing(this.state.spinValue, {                toValue: 1,                duration: 3000,                useNativeDriver: true,                delay: 2500            })        ).start()

what i want is to run animation, then wait 2500ms, then run again.

whats happening is animation first start takes 2500ms delay but further loop doesn't have that 2500ms delay

Android: PinchGestureHandler from react-native-gesture-handler not working

$
0
0

I am trying to implement PinchGesture Handler, but cannot figure out the issue why zooming is not happening,

Below is the code :

scale = new Animated.Value(0.3);return(<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><PinchGestureHandler                    onGestureEvent={this.onZoomEvent}                    onHandlerStateChange={this.onZoomStateChange}><Image                            source={{                            uri: imageUrl                            }}                            style={{                            width: width,                            height: 300,                            transform: [{ scale: 1 }]                            }}                            resizeMode='contain'                        /></PinchGestureHandler></View>        );

the function is also called , but zooming action not happening!

onZoomEvent = Animated.event(      [        {          nativeEvent: {scale: this.scale},        },      ],      {        useNativeDriver: true,      },    );    onZoomStateChange = event => {        if (event.nativeEvent.state === State.ACTIVE) {          Animated.spring(this.scale, {            toValue: 1,            useNativeDriver: true,          }).start();        }      };

React Native "RNCSafeAreaView" was not found in the UIManager

$
0
0

enter image description here

I am running a react-native application on Mac. but I am getting "RNCSafeAreaView" was not found in the UIManager.


How to convert text to speech in React-Native?

$
0
0

How to convert text to speech in react native TTS should be for dynamic text in real time.

How do I send data received in a FirebaseMessagingService java class to react native javascript?

$
0
0

I'm trying to create a react native Android app that can take firebase cloud messages.

Let's say I have created a java class that extends FirebaseMessagingService called MyFirebaseMessagingService and it can receive FCM messages. I know that to send the event to react native I can use RCTDeviceEventEmitter. To do this I also need the reactContext. How can I get the reactContext from within the MyFirebaseMessagingService class?

react-native run-android, Could not resolve all artifacts for configuration ':classpath'

$
0
0

I followed the intructions of React Native Getting Started, in the "Building Projects with Native Code" tab, for Windows and Android.

This is the content of the \AwesomeProject\android\build.gradle and after this there is the error I get when I execute: react-native run-android

// 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 {        google()        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:3.0.1'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        mavenLocal()        google()        jcenter()        maven {            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm            url "$rootDir/../node_modules/react-native/android"        }    }}task wrapper(type: Wrapper) {    gradleVersion = '4.7'    distributionUrl = distributionUrl.replace("bin", "all")}

When I execute: react-native run-android, I get the following error output:

D:\studio\study\reactnatv\AwesomeProject>react-native run-androidJS server already running.Building and installing the app on the device (cd android && gradlew.bat installDebug)...FAILURE: Build failed with an exception.* What went wrong:A problem occurred configuring root project 'AwesomeProject'.> Could not resolve all artifacts for configuration ':classpath'.> Could not find com.android.tools.build:gradle:3.0.1.     Searched in the following locations:         https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.pom         https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.jar         https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.pom         https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.jar     Required by:         project :* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.* Get more help at https://help.gradle.orgBUILD FAILED in 3sCould not install the app on the device, read the error above for details.Make sure you have an Android emulator running or a device connected and haveset up your Android development environment:https://facebook.github.io/react-native/docs/getting-started.htmlCommand failed: gradlew.bat installDebugError: Command failed: gradlew.bat installDebug    at checkExecSyncError (child_process.js:616:11)    at Object.execFileSync (child_process.js:634:13)    at runOnAllDevices (D:\studio\study\reactnatv\AwesomeProject\node_modules\react-native\local-cli\runAndroid\runAndroid.js:299:19)    at buildAndRun (D:\studio\study\reactnatv\AwesomeProject\node_modules\react-native\local-cli\runAndroid\runAndroid.js:135:12)    at isPackagerRunning.then.result (D:\studio\study\reactnatv\AwesomeProject\node_modules\react-native\local-cli\runAndroid\runAndroid.js:65:12)    at process._tickCallback (internal/process/next_tick.js:68:7)D:\studio\study\reactnatv\AwesomeProject>

I checked this US sanctions solution but it did not worked.

What am I doing wrong ?

React native ScrollView keyboardShouldPersistTaps not working Android

$
0
0

I have the following code, which works on my iOS app and keeps the keyboard open when clicking anywhere on the screen, but on Android it still closes the keyboard, any ideas?

return (<ScrollView                style={ styles.flex }                automaticallyAdjustContentInsets={ false }                keyboardShouldPersistTaps={ true }                contentInset={{ 'bottom':20 }}                keyboardDismissMode='on-drag'><View>...</View></ScrollView>        );

Is there a way to programatically trigger google voice to text functionality available via android keyboard?

Appstate keep on getting change in React native in Android

$
0
0

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

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

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

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

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

It goes on and never stop.

How to handle this? Any suggestions?

Different UI Design behaviour in react-native (expo)

$
0
0

I'M creating ui in expo application using react-native-paper. The UI is getting different for android and iOS platform for Account Screen. However, i tried same code in Snack and it show correct ui in web.

This is ios UIenter image description here

This is android UIenter image description here
In Android, some part of ui is hidden.


Snack Code Link

I need look like ios device screenshot have in android.


react native mapbox does not load map in release APK

$
0
0

Describe the bug

In my case Map is not displaying in release APK(Marker is showing properly). However debug build is ok.

I also have tested creating different token.

Example

import React, {Component} from 'react';import Mapbox, {MapView, Camera} from '@react-native-mapbox-gl/maps';import {Dimensions, Alert, View, Image, Platform} from 'react-native';const appConfig = require('../../../app.json');Mapbox.setAccessToken(appConfig.mapboxAccessToken);const {height, width} = Dimensions.get('window');class Map extends Component {  constructor(props) {    super(props);    this.state = {      basicSetup: {        showUserLocation: true,        centerCoordinate: [],        zoomLevel: 12,        maxZoomLevel: 19,        compassEnabled: true,        logoEnabled: false,        attributionEnabled: false,      },      disable: {        zoomEnabled: false,        scrollEnabled: false,        pitchEnabled: false,        rotateEnabled: false,      },    };  }  render() {    return (<View style={[styles.map, style]}><MapView          styleURL={appConfig['someconfigname']}          style={{flex: 1}}          ref={(ref) => {            this.control = ref;          }}><Camera ref={(c) => (this.camera = c)} zoomLevel={14} />          {children}</MapView>        {hideLogo ? null : (<View style={[styles.logo, logoStyle]}><Image              resizeMode={'contain'}              source={require('../../../resources/images/map_logo.png')}              style={{flex: 1}}            /></View>        )}</View>    );  }}export default Map;const styles = {  map: {    width,    height,  },  logo: {    position: 'absolute',    bottom: Platform.OS == 'ios' ? 20 : 40,    left: 20,    shadowColor: '#37474f',    shadowOpacity: 0.24,    shadowOffset: {height: 2, width: 0},    elevation: 3,    shadowRadius: 3,  },  circle: {    position: 'absolute',    borderWidth: 1,    borderColor: '#111',    backgroundColor: '#03111111',    justifyContent: 'center',    alignItems: 'center',  },  circleCenter: {    height: 4,    width: 4,    borderRadius: 4,    backgroundColor: '#a1a5d1',  },  radiusText: {    fontSize: 13.47,    color: '#a1a5d1',  },};

Expected behavior

It should display map even though it is in release mode

Screenshots

======= Debug mode =======enter image description here

======= Release Mode =======enter image description here

Platform: [Android]

Device: [One Plus 7T]

Emulator/ Simulator: [no]

OS: [Android 9]

react-native-mapbox-gl Version [8.1.0-rc.1]

React Native Version [0.62.2]

OpenCV Android React Native unknown exception on some functions in imgproc module

$
0
0

I'm trying to use OpenCV in an mobile app written with React Native. For now i only focus on the Android part. I use the official OpenCV for Android release. I did add the sdk, modified my MainApplication.java and wrote some wrapping methods that can be called from React Native. So far this compiles and works as expected.

Now the problem is that if get an unknown exception from some OpenCV functions, others work fine. E.g. when I call the blur(), medianBlur() or warpAffine() functions from the Imgproc module everything is well. When i try to call e.g. the gaussianBlur() or Canny() functions i get an unknown exception thrown from OpenCV.

I really have no idea what the problem is. The sdk seems to be linked correctly as i can booth compile the app and run several functions.

My Setup:

  • Development on Arch Linux
  • OpenCV 4.3.0 for Android
  • React Native 0.62.2
  • Compiled with gradle/react-native from terminal
  • Android 10

Example error when i try to run the Canny() function:

org.opencv.imgproc: imgproc::Canny_12() caught unknown exceptionunknown exceptionjava.lang.Exception: unknown exception    at org.opencv.imgproc.Imgproc.Canny_2(Native Method)    at org.opencv.imgproc.Imgproc.Canny(Imgproc.java:2662)    at com.rnopencv.RNOpenCvLibraryModule.cannyEdges(RNOpenCvLibraryModule.java:110)    at java.lang.reflect.Method.invoke(Native Method)    at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)    at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:151)    at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)    at android.os.Handler.handleCallback(Handler.java:883)    at android.os.Handler.dispatchMessage(Handler.java:100)    at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)    at android.os.Looper.loop(Looper.java:214)    at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)    at java.lang.Thread.run(Thread.java:919)

calling the following wrapper:

@ReactMethod    public void cannyEdges(String imageAsBase64, int treshold, Promise promise) {        try {            // Constants            Size BLUR_SIZE = new Size(3,3);            int KERNEL_SIZE = 3;            int RATIO = 3;            int MAX_LOW_THRESHOLD = 100;            int lowTreshold = (treshold <= MAX_LOW_THRESHOLD) ? treshold : MAX_LOW_THRESHOLD;            // decode base64 string to matrix            Bitmap srcImage = base64ImageToBitmap(imageAsBase64);            Mat srcMat = new Mat();            Utils.bitmapToMat(srcImage, srcMat);            // rotate image to be portrait            Mat orientedMat = rotateBoxed(srcMat, -90);            // blur the image            Mat bluredMat = new Mat();            Mat cannyMat = new Mat();            Imgproc.blur(orientedMat, bluredMat, BLUR_SIZE);            // NEXT LINE THROWS THE ERROR            Imgproc.Canny(bluredMat, cannyMat, lowTreshold, lowTreshold * RATIO, KERNEL_SIZE, false);            // return blured image wrapped in promise            Bitmap dstImage = Bitmap.createBitmap(cannyMat.cols(), cannyMat.rows(), srcImage.getConfig());            Utils.matToBitmap(cannyMat, dstImage);            promise.resolve(bitmapToBase64(dstImage));        } catch (Exception e) {            System.out.println("Oh snap, some Exception occured!");            System.out.println(e.getMessage());            e.printStackTrace(System.out);            promise.reject("Could not perform canny edge detection on image!", e);        }    }

The wrapper gets the image as base64 encoded String (don't have a better solution yet) and returns the result in a js Promise. I also rotate the image to correct orientation using an affine transformation (this part works like described above). I tried various values for threshold, same goes for the gaussianBlur() method. The result is always either an assertion failure for invalid parameters (which is expected) or the mysterious unknown exception.

Any clues on what the problem might be?

How to scroll parent ScrollView while child is moving in it using PanResponder

$
0
0

I am looking for an option to build this functionality in react native.

enter image description here

I have added PanResponder inside a scroll view but the problem is when I drag an item in screen scroll view does not scroll. So is there any option available in react-native to drag and scroll at the same time to achieve the same view.

How to integrate codepush with react native(with redux)

$
0
0

I'm learning react native and came across with codepush and redux.I'm looking for an answer of integrating both codepush and redux on a react native app(android).

It's 3 weeks I have submitted my projects in cs50 app development and not graded

$
0
0

I have submitted my cs50 app development projects 3 weeks before but it's not graded yet. I have also filled the form with a youtube video. It says that it will took upto 3 weeks but not yet graded. Can someone please tell what should I do?

Viewing all 28482 articles
Browse latest View live


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