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

React Native Rendering Image borderRadius in iOS

$
0
0

Images are rendered in different aspects in ios and android using image component from react-native. I’m trying to display image with 45 degree angle cutoff every corner.

I have tried to use cover, contain and center of the resizeMode prop cover fills the image inside the view giving the 45 degree cut but crops either width or height.

Center does not crop the image but if the image isn’t similar ratio as the view the 45 degree angles aren’t cut of the image, Android does this well though.

<View style={(this.state.controlsDisplayed) ? styles.flexLR : styles.flexLRBlack}><View style={{flex: (Platform.OS === ‘ios’) ? 0.85 : 0.5}} /><View style={styles.imageWrapView}><Image source={{uri: ‘file://’+ item.photoLeft}} key={“TDVIEW”} resizeMode={(Platform.OS == ‘ios’) ? ‘cover’ : ‘center’} style={styles.floatingImagePartView} /></View><View style={{flex: (Platform.OS === ‘ios’) ? 0.85 : 0.5}} /></View>

Want to get uncropped images on ios that have corners cut of by 45 degrees. Same as is in the android images. Here are images from android device that are rendered correctly.

android1 cutoff

android1 image

Here are the images rendered on ios using center and cover

android1 cutoff

This is rendered using contain on ios

android1 cutoff

android1 image

How can I get the images rendered with 45 degree cutoff on ios device as it is on an android device?


Android Studio is building old version via Generate Signed bundle / APK

$
0
0

I am trying to build APK from Android studio 3.6.3 to test on the device as well as for publishing app on google play console, but I noticed, Its building APK with the old version, tried almost everything

By the way, build is working fine on the built-in emulator

build.gradle

// The old version name was 1.1defaultConfig {    applicationId "com.bankonus"    minSdkVersion rootProject.ext.minSdkVersion    targetSdkVersion rootProject.ext.targetSdkVersion    versionCode 3    versionName "1.2"    missingDimensionStrategy 'react-native-camera', 'general'    multiDexEnabled true}

Tried solutions

  1. File > Invalidate cache/restart > Invalidate cache/restart
  2. Build > Clean project
  3. Run > Edit Configuration > app > general > before launch > Gradle-aware make

Please help, Thanks in advance

React Native Picker select: are there any callbacks available for Android?

$
0
0

I'm using react-native-picker-select in my React Native app, and the two main callbacks I'm using for iOS are onClose() and onDonePress(). However, these are iOS only. Is there some approach you can use with Android to trigger a function when the user has closed the picker or pressed Done? I know you can use onValueChange(), but this doesn't get triggered when the user is done, just when they iterate through the options in the picker.

TouchableOpacity not working on expo for react native not working

$
0
0

Am working on this login page where I had to use TouchableOpacity on a this text "Already have an account? Sign in instead!" to send me to the singin screen and for some reason it didn't work so naturally I thought I had an error in my code and after hours of debugging I had the idea to make a simple button with the same functionality and it works for am wondering is there something wrong with TouchableOpacity on expo or there is somekind of logic error i missed.

here is the code i used :

From my signup screen :

return (<View style={styles.container}><NavigationEvents onWillBlur={clearErrorMessage} /><AuthForm        headerText="Sign Up for Tracker"        errorMessage={state.errorMessage}        submitButtonText="Sign Up"        onSubmit={signup}      /><NavLink        routeName="Signin"        text="Already have an account? Sign in instead!"      /></View>  );

from the Navlink component :

return (<><TouchableOpacity onPress={() => navigation.navigate(routeName)}><Spacer><Text style={styles.link}>{text}</Text></Spacer></TouchableOpacity><Button        title="go to sing in"        onPress={() => {          navigation.navigate("Singin");        }}      /></>  );

Pan Responder simply not working on Android

$
0
0

I am on React Native .61.

I am trying to use a library that uses Pan Responder, and it just is not working.

This is my code:

<Swiper                    ref={this.swiper}                    onSwiped={(cardIndex) => this.onSwiped('general', cardIndex)}                    onSwipedLeft={(cardIndex) => this.onSwiped('left', cardIndex)}                    onSwipedRight={(cardIndex) => this.onSwiped('right', cardIndex)}                    cards={this.state.offers}                    cardIndex={this.state.cardIndex}                    cardVerticalMargin={20}                    infinite={true}                    disableTopSwipe={true}                    disableBottomSwipe={true}                    renderCard={this.renderCard}                    onSwipedAll={this.onSwipedAllCards}                    stackSize={3}                    stackSeparation={15}                    overlayLabels={{                        left: {                            title: 'NOPE',                            style: {                                label: {                                    backgroundColor: 'black',                                    borderColor: 'black',                                    color: 'white',                                    borderWidth: 1                                },                                wrapper: {                                    flexDirection: 'column',                                    alignItems: 'flex-end',                                    justifyContent: 'flex-start',                                    marginTop: 30,                                    marginLeft: -30                                }                            }                        },                        right: {                            title: 'LIKE',                            style: {                                label: {                                    backgroundColor: 'black',                                    borderColor: 'black',                                    color: 'white',                                    borderWidth: 1                                },                                wrapper: {                                    flexDirection: 'column',                                    alignItems: 'flex-start',                                    justifyContent: 'flex-start',                                    marginTop: 30,                                    marginLeft: 30                                }                            }                        },                    }}                    animateOverlayLabelsOpacity                    animateCardOpacity                    swipeBackCard></Swiper><Buttons onSwiped={this.onSwiped} {...this.props} swiper={this.swiper} />

This is pan responder usage inside the module:

initializePanResponder = () => {    this._panResponder = PanResponder.create({      onStartShouldSetPanResponder: (event, gestureState) => true,      onMoveShouldSetPanResponder: (event, gestureState) => true,      onMoveShouldSetPanResponderCapture: (evt, gestureState) => {        const isVerticalSwipe = Math.sqrt(          Math.pow(gestureState.dx, 2) < Math.pow(gestureState.dy, 2)        )        if (!this.props.verticalSwipe && isVerticalSwipe) {          return false        }        return Math.sqrt(Math.pow(gestureState.dx, 2) + Math.pow(gestureState.dy, 2)) > 10      },      onPanResponderGrant: this.onPanResponderGrant,      onPanResponderMove: this.onPanResponderMove,      onPanResponderRelease: this.onPanResponderRelease,      onPanResponderTerminate: this.onPanResponderRelease    })  }onPanResponderGrant = (event, gestureState) => {    this.props.dragStart && this.props.dragStart()    if (!this.state.panResponderLocked) {      this.state.pan.setOffset({        x: this._animatedValueX,        y: this._animatedValueY      })    }    this.state.pan.setValue({      x: 0,      y: 0    })  }onPanResponderMove = (event, gestureState) => {    this.props.onSwiping(this._animatedValueX, this._animatedValueY)    let { overlayOpacityHorizontalThreshold, overlayOpacityVerticalThreshold } = this.props    if (!overlayOpacityHorizontalThreshold) {      overlayOpacityHorizontalThreshold = this.props.horizontalThreshold    }    if (!overlayOpacityVerticalThreshold) {      overlayOpacityVerticalThreshold = this.props.verticalThreshold    }    let isSwipingLeft,      isSwipingRight,      isSwipingTop,      isSwipingBottom    if (Math.abs(this._animatedValueX) > Math.abs(this._animatedValueY) && Math.abs(this._animatedValueX) > overlayOpacityHorizontalThreshold) {      if (this._animatedValueX > 0) isSwipingRight = true      else isSwipingLeft = true    } else if (Math.abs(this._animatedValueY) > Math.abs(this._animatedValueX) && Math.abs(this._animatedValueY) > overlayOpacityVerticalThreshold) {      if (this._animatedValueY > 0) isSwipingBottom = true      else isSwipingTop = true    }    if (isSwipingRight) {      this.setState({ labelType: LABEL_TYPES.RIGHT })    } else if (isSwipingLeft) {      this.setState({ labelType: LABEL_TYPES.LEFT })    } else if (isSwipingTop) {      this.setState({ labelType: LABEL_TYPES.TOP })    } else if (isSwipingBottom) {      this.setState({ labelType: LABEL_TYPES.BOTTOM })    } else {      this.setState({ labelType: LABEL_TYPES.NONE })    }    const { onTapCardDeadZone } = this.props    if (      this._animatedValueX < -onTapCardDeadZone ||      this._animatedValueX > onTapCardDeadZone ||      this._animatedValueY < -onTapCardDeadZone ||      this._animatedValueY > onTapCardDeadZone    ) {      this.setState({        slideGesture: true      })    }    return Animated.event([null, this.createAnimatedEvent()])(      event,      gestureState    )  }  onPanResponderRelease = (e, gestureState) => {    this.props.dragEnd && this.props.dragEnd()    if (this.state.panResponderLocked) {      this.state.pan.setValue({        x: 0,        y: 0      })      this.state.pan.setOffset({        x: 0,        y: 0      })      return    }    const { horizontalThreshold, verticalThreshold } = this.props    const animatedValueX = Math.abs(this._animatedValueX)    const animatedValueY = Math.abs(this._animatedValueY)    const isSwiping =      animatedValueX > horizontalThreshold || animatedValueY > verticalThreshold    if (isSwiping && this.validPanResponderRelease()) {      const onSwipeDirectionCallback = this.getOnSwipeDirectionCallback(        this._animatedValueX,        this._animatedValueY      )      this.swipeCard(onSwipeDirectionCallback)    } else {      this.resetTopCard()    }    if (!this.state.slideGesture) {      this.props.onTapCard(this.state.firstCardIndex)    }    this.setState({      labelType: LABEL_TYPES.NONE,      slideGesture: false    })  }

I've been trying to figure this out all day - for some reason the library just does not work on Android.

I've considered switching it out for another one or writing my own, but I already have my iOS code working and I'm loathe to totally replace it, especially when my guess is that it is a fairly simple Pan Responder issue.

The library in question is this one:

https://github.com/alexbrillant/react-native-deck-swiper

com.rnfs.RNFSManager.mkdir: java.lang.Exception: Directory could not be created

$
0
0

https://github.com/itinance/react-native-fs

code

import RNFS from 'react-native-fs';RNFS.mkdir(RNFS.ExternalDirectoryPath + dir)

logcat

05-06 22:43:41.693  W/System.err: java.lang.Exception: Directory could not be created05-06 22:43:41.697  W/System.err:     at com.rnfs.RNFSManager.mkdir(RNFSManager.java:680)

This error occurs after compilation,

But it is normal when debugging,

Disable Screen Capture/ScreenShot in React Native App

$
0
0

I have came across few solutions specific for ios and Android to prevent screen-capturing and taking screenshots. But how do i disable screen-capturing in react native?

Alternative of Googlesignin and FBlogin for china

$
0
0

I a developing an app using react-native and added googlesignin ad FBlogin for authentication purpose. But soon I came to know that both are banned in china. Is there any other alternative for third part authentication service for Chinese people.


Save sensitive data in React Native

$
0
0

I am building a React Native application and I need to save some sensitive data like a token and a refresh token. The obvious solution is to save that information using AsyncStorage. The problem is the security level of the AsyncStorage.

AsyncStorage provides a way to locally store tokens and data. It can be, in some ways, compared to a LocalStorage option. In full production applications, it is recommended to not access AsyncStorage directly, but instead, to use an abstraction layer, as AsyncStorage is shared with other apps using the same browser, and thus an ill-conceieved removal of all items from storage could impair the functioning of neighboring apps.

https://auth0.com/blog/adding-authentication-to-react-native-using-jwt/

In a native app, I would go for Keychain in iOS and Shared Preferences in private mode in Android.

For what I read in the documentation provided by React Native:

On iOS, AsyncStorage is backed by native code that stores small values in a serialized dictionary and larger values in separate files. On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.

https://facebook.github.io/react-native/docs/asyncstorage.html

They never talk about the security of that data.

It is the best solution create a module for Android (that uses Shared Preferences in private mode) and another for iOS (that uses Keychain) to save the sensible data? Or it is safe to use the AsyncStorage methods provided?

Smooth Orientation Compass using react-native-sensors's Magnetometer

$
0
0

I'm developing a compass app using react-native-sensors magnetometer. I'm getting the correct values and the compass is working perfectly, the main problem is the fast update of the compass, the direction keeps changing too frequently and the change is +-5 degrees.I want to do a smooth orientation compass.

_angle = (magnetometer) => {    if (magnetometer) {      let { x, y, z } = magnetometer      if (Math.atan2(y, x) >= 0) {        angle = Math.atan2(y, x) * (180 / Math.PI)      } else {        angle = (Math.atan2(y, x) + 2 * Math.PI) * (180 / Math.PI)      }    }    return Math.round(angle)  }//Inside ComponentDidMountmagnetometer.subscribe(({ x, y, z, timestamp }) =>      this.setState({ sensorValue: this._angle({ x, y, z }) })

How to change styling of TextInput placeholder in React Native?

$
0
0

Is there a way to set fontStyle: 'italic'only for the placeholder of the TextInput in React Native?

looking here at the documentation seems like you can only set a placeholder and placeholderTextColor.

How to create global android device back button handler using React Native?

$
0
0

In my scenario, I am trying to create global class for android back button handler and reuse it in multiple screen class files. How to do it? I tried below code but I dont know how to access common class from other classes.

My Code Below (Androidhandler.tsx)

export default class hardware extends Component {  constructor(props) {    super(props);    this.BackButton = this.BackButton.bind(this);  }  componentWillMount() {    BackHandler.addEventListener'BackPress',this.BackButton);  }  componentWillUnmount() {    BackHandler.removeEventListener('BackPress',this.BackButton);  }  BackButton() {    if(this.props.navigation){        this.props.navigation.goBack(null);        return true;      }    }}

How to implement Android ContentProvider in React Native?

$
0
0

I need ContentProvider for my android application to share data with other applications. It seems like React Native doesn't support it yet. I checked the official documentation but was unable to find any clue.

In this scenario, I have two options. The first one to check for any Native Module that offers the support for ContentProvider in React Native. Again I didn't find any module that can help me.

So the last option I am left with is to build a Native Module for ContentProvider on my own.

Do you have any idea about android ContentProvider support in ReactNative?

What would you suggest to me in this scenario?

Expected dynamic type `double', but had type `null' (Constructing arguments for Timing.createTimer at index 1)

$
0
0

I have been getting this error Expected dynamic type `double', but had type `null' (Constructing arguments for Timing.createTimer at index 1) when I run react-native android. When I try locating Timing.createTimer I found it that it's being used in 3 places inside node_modules/react-native/Libraries/Core/Timers/JSTimers.js:

1

setTimeout: function(func: Function,duration: number,...args?: any): number {    if (__DEV__ && IS_ANDROID && duration > MAX_TIMER_DURATION_MS) {      console.warn(        ANDROID_LONG_TIMER_MESSAGE +'\n'+'(Saw setTimeout with duration '+          duration +'ms)',      );    }    const id = _allocateCallback(      () => func.apply(undefined, args),'setTimeout',    );    Timing.createTimer(id, duration || 0, Date.now(), /* recurring */ false);    return id;  }

2

setInterval: function(func: Function,duration: number,...args?: any): number {    if (__DEV__ && IS_ANDROID && duration > MAX_TIMER_DURATION_MS) {      console.warn(        ANDROID_LONG_TIMER_MESSAGE +'\n'+'(Saw setInterval with duration '+          duration +'ms)',      );    }    const id = _allocateCallback(      () => func.apply(undefined, args),'setInterval',    );    Timing.createTimer(id, duration || 0, Date.now(), /* recurring */ true);    return id;  }

3

  requestAnimationFrame: function(func: Function) {    const id = _allocateCallback(func, 'requestAnimationFrame');    Timing.createTimer(id, 1, Date.now(), /* recurring */ false);    return id;  }

invoke method is define inside JavaMethodWrapper.java 368 line

   @Override   public void invoke(JSInstance jsInstance, ReadableNativeArray parameters) {    ....        try {            for (; i < mArgumentExtractors.length; i++) {              mArguments[i] = mArgumentExtractors[i].extractArgument(                jsInstance, parameters, jsArgumentsConsumed);              jsArgumentsConsumed += mArgumentExtractors[i].getJSArgumentsNeeded();            }          } catch (UnexpectedNativeTypeException e) {            throw new NativeArgumentsParseException(              e.getMessage() +" (constructing arguments for "+ traceName +" at argument index "+                getAffectedRange(jsArgumentsConsumed, mArgumentExtractors[i].getJSArgumentsNeeded()) +")",              e);          }....}

And it's being called from JavaModuleWrapper.java 162

    @DoNotStrip  public void invoke(int methodId, ReadableNativeArray parameters) {    if (mMethods == null || methodId >= mMethods.size()) {      return;    }    mMethods.get(methodId).invoke(mJSInstance, parameters);  }

Things I tried:

  1. Tried guarding against a null id before Timing.createTimer is being called by doing if (id == null || id = '') { return null }
  2. Tried printing the id that was being set before Timing.createTimer, but it caused the app to stop responding since it's triggering almost every second

Any help will be much appreciated. Thanks in advance

PS: I read about every post there is related to this problem couldn't find a solution that applies

TouchableOpacity not working on expo for react native

$
0
0

Am working on this login page where I had to use TouchableOpacity on a this text "Already have an account? Sign in instead!" to send me to the singin screen and for some reason it didn't work so naturally I thought I had an error in my code and after hours of debugging I had the idea to make a simple button with the same functionality and it works for am wondering is there something wrong with TouchableOpacity on expo or there is somekind of logic error i missed.

here is the code i used :

From my signup screen :

return (<View style={styles.container}><NavigationEvents onWillBlur={clearErrorMessage} /><AuthForm        headerText="Sign Up for Tracker"        errorMessage={state.errorMessage}        submitButtonText="Sign Up"        onSubmit={signup}      /><NavLink        routeName="Signin"        text="Already have an account? Sign in instead!"      /></View>  );

from the Navlink component :

return (<><TouchableOpacity onPress={() => navigation.navigate(routeName)}><Spacer><Text style={styles.link}>{text}</Text></Spacer></TouchableOpacity><Button        title="go to sing in"        onPress={() => {          navigation.navigate("Singin");        }}      /></>  );

How to set android:icon dynamically

$
0
0

I'm using react-native-config to be able to build using different environments. One of the purposes is to have different icons depending on the environment. I got this to work on iOS but having trouble on Android.

I have a @string resource:<string name="exchange_name">@string/REACT_APP_EXCHANGE_NAME</string>

The REACT_APP_EXCHANGE_NAME variable is inserted from my .env file (react-native-config magic).My question is how can I have different icons depending on the value of that string resource?

Something like:android:icon={exchange_name == 'something' ? @mipmap/icon1 : @mipmap/icon2}

How to move an element to the pressed position in react-native

$
0
0

I want to move and element right to place I click with onPress event.

Example if I click on the screen with position x: 200, y: 300, so my element should move there from position x: -100, y: -100, I tried it, but it is not moving to the exact position I press on the screen. my code:, although it moves, but moves not exactly to the place I want...

const styles = StyleSheet.create({    alertAutoCloseContainer: {        left: 0, top: 0,        margin: 10, marginHorizontal: 40, position: 'absolute',        padding: 10, maxWidth: 500, maxHeight: 400, zIndex: 1000,        backgroundColor: 'rgba(0, 50, 50, 0.8)', borderRadius: 5,    },    alertAutoCloseText: {        color: '#fff', fontFamily: 'IRANSansMobile'    }});const { Value } = Animated;const animatedValue = new Value(0);const MyAlert = memo(forwardRef(({ }, ref) => {    const [state, setState] = useReducer((s, v) => v, {        status: true, xAxis: 0, yAxis: 0, parentData: {            text: ""        }    });    useImperativeHandle(ref, () => {        return ({            startAnimation: ({ xAxis, yAxis, parentData }) => {                const { status } = state;                setState({                    ...state, xAxis, yAxis,                    parentData, status: !status                });                Animated.timing(animatedValue, {                    toValue: status === true ? 1 : 0, duration: 500                }).start();            },            stopAnimation: ({ }) => {                Animated.timing(animatedValue, {                    toValue: 0, duration: 500                }).start();            }        })    });    console.log(state.xAxis, state.yAxis);    return (<Animated.View style={{            ...styles.alertAutoCloseContainer, transform: [                {                    translateY: animatedValue.interpolate({                        inputRange: [0, 1],                        outputRange: [0, state.yAxis],                        extrapolate: 'clamp'                    })                },                {                    translateX: animatedValue.interpolate({                        inputRange: [0, 1],                        outputRange: [0, state.xAxis],                        extrapolate: 'clamp'                    })                },                {                    scale: animatedValue.interpolate({                        inputRange: [0, 1],                        outputRange: [0, 1]                    })                }            ]        }}><Text style={styles.alertAutoCloseText}>                {state.parentData.text}</Text></Animated.View>    );}), (p, n) => true);

How to update version number of react native app

$
0
0

I am using React native with Android. How can I update version number in the app? As I am getting this error.

I am generating file as per this urlhttps://facebook.github.io/react-native/docs/signed-apk-android.html

I have tried modifying AndroidManifest.xml file, but after I build it, that file gets automatically modified back.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.facebook.react"    android:versionCode="1"    android:versionName="1.0">

Here, I modified the XML:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.facebook.react"    android:versionCode="2"    android:versionName="1.1">

After, build file automatically changes back.

enter image description here

Could not get unknown property 'mergeResourcesProvider' for object of type com.android.build.gradle.internal.api.ApplicationVariantImpl

$
0
0

I want to integrate webrtc in my react-native application ,Installed the package for react-native react-native-webrtc.Finished all the steps mentioned in the documentation ,But im getting error message

Could not get unknown property 'mergeResourcesProvider' for object of type com.android.build.gradle.internal.api.ApplicationVariantImpl. What will be the reason for the error.terminal view while run "react-native run-android"

Task :app:bundleReleaseResources FAILED when trying to ./gradlew bundleRelease

$
0
0

I am trying to get the .aab and the .apk files to publish the android side of a react-native app to the Google Play Store. I have followed all the directions on the React-Native Docs but when I run ./gradlew bundleRelease it fails.

After about 2 minutes of working Task :app:bundleReleaseResources FAILED is printed.

It gives a little more information but I have been unable to find anything that fixes this error.

Execution failed for task ':app:bundleReleaseResources'.> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade> AAPT2 aapt2-3.6.3-6040484-osx Daemon #0: Unexpected error during link, attempting to stop daemon.     This should not happen under normal circumstances, please file an issue if it does.

I have also run the app in android studio and get the same error. I am especially confused because the app works when I run the nix react-native run-android command.

If any more information is needed please let me know and thank you in advance for any help!

Viewing all 28469 articles
Browse latest View live


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