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

react-native-geolocation-service build issue

$
0
0

Problem:

I have a react native application, there I am using react-native-geolocation-service. After having npm install I tried to build the project using The android studio in there It failed and led me to an error like this.

error: cannot find symbol variable ActivityCompat

This is my build Gradle file.

// 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
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.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://jitpack.io' }
    }
}

I tried a lot to find a solution to this problem on the Internet but I was not able to do so. So can someone help me to solve this issue? Thank you


Expo: don't show notification if app is open in foreground

$
0
0

I am developing a react-native messaging app with Expo. Every time a user receives a new message, I send a notification from my server.

Is there any way to not display the notification if the app is currently open?

Right now I am using this as soon as the notification is received:

Notifications.dismissNotificationAsync(notification.notificationId);

But there is a 0.5 second delay where the notification has time to appear in the tray and trigger a sound before it gets dismissed. I would like to not show it at all.

Expo - Build android app-bundle with "app signing" certificates

$
0
0

I have an already published (to Google Play) APK that was built by Expo. The key was also created by Expo. Until now everything works great.

I tried to build an app-bundle because now it is the recommended way to build apps for Android. It also helps to reduce app size.

I followed this documentation (that is not 100% clear). I ran expo opt-in-google-play-signing and followed the instructions. Eventually the certificates in Google Console were created successfully.

In Release Management > App Signing it now says "App signing by Google Play is enabled for this app".

But it looks like those certificates were not successfully uploaded to Expo (I am not sure if this is the problem).

I am building the app-bundle with this command: expo build:android -t app-bundle.

But the problem is when I am trying to upload the app-bundle in the Release Management in the console it says that the app is signed with a wrong upload certificate.

I tried everything that I was able to find in the searches but nothing helped.

I am completely lost. Can someone please instruct me how I can correctly build the app-bundle and successfully upload it to Google Play?

RNCamera Error:TypeError: CameraManager.checkIfRecordAudioPermissionsAreDefined is not a function

$
0
0

[Unhandled promise rejection: TypeError: CameraManager.checkIfRecordAudioPermissionsAreDefined is not a function. (In 'CameraManager.checkIfRecordAudioPermissionsAreDefined()', 'CameraManager.checkIfRecordAudioPermissionsAreDefined' is undefined)]

return (
  <View>
    <Text>Welcome to React Native QRScanner!</Text>

    <RNCamera
      ref={ref => {
        this.camera = ref;
      }}
      style={{
        flex: 1,
        width: '100%'
      }}
      androidRecordAudioPermissionOptions={{
        title: 'Permission to use audio recording',
        message: 'We need your permission to use your audio',
        buttonPositive: 'Ok',
        buttonNegative: 'Cancel',
      }}
      onBarCodeRead={this.barcodeRecognized}
    >

    </RNCamera>
  </View>
);

One Specific API call fails only on Android ( react-native )

$
0
0

I have a react-native app that logs in and grabs user information based on the following code:

TestCall(){
    console.log(`${myLocation}/login`);
        return fetch(`${myLocation}/login`, {

            method:'POST',
            headers: {Accept: 'application/json',
                        'Content-Type': 'application/json',
        },
        credentials: "include",
        body: JSON.stringify({
            email:this.state.email,
            password:this.state.password,
        })
        })
  .then(response => response.json())
  .then(json => console.log(json))
}

I have different options for myLocation because I'm using this to grab account info from multiple sites that all allow login based on email and password. All start with https. This works perfectly for IOS no matter what I'm using for myLocation. This works perfectly on Android for all except for one option for myLocation.

For this specific combination of this specific myLocation and Android I get 'Network Request Failed' no matter which user account I try. This includes user account/myLocation combos that work on IOS. It's not giving me a 400, or 404, or 500 or anything like that because it's not even getting that far. When I use catch to see what's happening it just goes straight to the catch and always gives me the 'Network Request Failed' as the error that's being logged.

Also, I am using Android emulator and IOS simulator on the same computer so IP gateway and IP address are the same for both. Only user agent is different (okhttp for android and CFNetwork Darwin for IOS). I'm stumped. Does anyone know why this would be happening? Thanks!

How to sign Expo app APK to update existing App on Google Play Store?

$
0
0

I have an EXPO app and I already created and published it on Google Play Store. The Google App Signing is activated for this project. Now I want to update this APK in this project. I used the command 'expo build:android' to build the updated APK. But when I send it to my project on Play store, it says that the certificate is wrong ('Upload failed You uploaded an APK that is signed with a different certificate to your previous APKs. You must use the same certificate').

RNCamera - onFaceDetectionError not working in both Android and iOS

$
0
0

I am not able to find not detecting the face scenario using RNCamera.

dependencies: "react-native": "0.61.5", "react-native-camera": "git+https://git@github.com/react-native-community/react-native-camera.git",

this is how I am using the RNCamera, ....

<RNCamera 
      ref={ref => {this.camera = ref}}
      type={RNCamera.Constants.Type.front}
      onFacesDetected={this.handleFaceDetected}
      onFaceDetectionError = {this.faceDetectionError}
    </RNCamera>
    ...
    handleFaceDetected = (faces) => {
            console.log('face detected!')
        }

    faceDetectionError = (error) => {
            console.log('face Not detected!')
        }

I also faced that even though the camera is not in front of any faces, in some of the android devices it is triggering the onFacesDetected method.

Any help in this is much thankful. Thanks in advance.

React native App on android stops execution of react-native-background-timer when device is locked

$
0
0

I am call a function which is call in background continuously.but when app is locked this function is not call. I used react-native-background-timer to do call in background. Please help me to solve this issue.


Why gaves me error Module AppRegistry error react native expo

$
0
0

A few days ago everything was going well, everything was running perfectly and I got this error out of nowhere, and I tried to update all the modules, reinstall expo-cli, delete and install the modules again, however without results.

Photo error pic:here

Console output:here

Output console logs:

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli 'C:\Program Files\nodejs\node.exe',
1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'start'
1 verbose cli ]
2 info using npm@6.12.1
3 info using node@v12.13.1
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle @~prestart: @
6 info lifecycle @~start: @
7 verbose lifecycle @~start: unsafe-perm in lifecycle true
8 verbose lifecycle @~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\Shair\Desktop\fastly-app\node_modules.bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Users\Shair\bin;C:\Python27;C:\Python27\Scripts;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\ProgramData\chocolatey\bin;C:\Program Files\nodejs;C:\Program Files\Git\cmd;C:\Program Files (x86)\Yarn\bin;C:\Users\Shair\AppData\Local\Microsoft\WindowsApps;C:\Users\Shair\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\Shair\AppData\Roaming\npm;C:\Users\Shair\AppData\Local\Yarn\bin
9 verbose lifecycle @~start: CWD: C:\Users\Shair\Desktop\fastly-app
10 silly lifecycle @~start: Args: [ '/d /s /c', 'expo start' ]
11 silly lifecycle @~start: Returned: code: 1 signal: null
12 info lifecycle @~start: Failed to exec start script
13 verbose stack Error: @ start: expo start
13 verbose stack Exit status 1
13 verbose stack at EventEmitter. (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack at EventEmitter.emit (events.js:210:5)
13 verbose stack at ChildProcess. (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:210:5)
13 verbose stack at maybeClose (internal/child_process.js:1021:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
14 verbose pkgid @
15 verbose cwd C:\Users\Shair\Desktop\fastly-app
16 verbose Windows_NT 10.0.18363
17 verbose argv "C:\Program Files\nodejs\node.exe""C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js""start"
18 verbose node v12.13.1
19 verbose npm v6.12.1
20 error code ELIFECYCLE
21 error errno 1
22 error @ start: expo start
22 error Exit status 1
23 error Failed at the @ start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

My expo diagnostics: here

Also here's my app.json, package.json and App.js respectively:

{
  "expo": {
    "name": "Fastly",
    "slug": "fastly-app",
    "privacy": "public",
    "sdkVersion": "36.0.0",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "androidStatusBarColor": "#ffffff",
    "androidStatusBar": {
      "barStyle": "dark-content",
      "backgroundColor": "#ffffff"
    },
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/images/icon.png",
    "splash": {
      "image": "./assets/images/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "ios": {
      "supportsTablet": true
    },
    "facebookAppId": "2353635448075929",
    "facebookDisplayName": "Fastly",
    "android": {
      "package": "com.shair.fastly"
    }
  }
}
{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "test": "jest --watchAll"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/samples": "~36.0.0",
    "@expo/vector-icons": "~10.0.0",
    "@react-navigation/web": "~1.0.0-alpha.9",
    "expo": "~36.0.0",
    "expo-asset": "~8.0.0",
    "expo-constants": "^8.0.0",
    "expo-facebook": "~8.0.0",
    "expo-font": "~8.0.0",
    "expo-permissions": "^8.0.0",
    "expo-web-browser": "~8.0.0",
    "firebase": "^7.6.1",
    "native-base": "^2.13.8",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-paper": "^3.4.0",
    "react-native-reanimated": "~1.4.0",
    "react-native-screens": "2.0.0-alpha.12",
    "react-native-web": "~0.11.7",
    "react-navigation": "~4.0.10",
    "react-navigation-drawer": "^2.3.3",
    "react-navigation-material-bottom-tabs": "^2.1.5",
    "react-navigation-stack": "~1.10.3",
    "react-navigation-tabs": "~2.6.2",
    "react-redux": "^7.1.3",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "babel-preset-expo": "~8.0.0",
    "jest-expo": "~36.0.1"
  },
  "private": true
}

/** React bundle */
import React, { Component } from 'react'
import { View } from 'react-native'

import { createStore, combineReducers, applyMiddleware } from 'redux'

import ReduxThunk from 'redux-thunk'

import { Provider } from 'react-redux'

import { Root } from 'native-base'

import * as Font from 'expo-font'

/** Navigation */
import { createAppContainer, createSwitchNavigator } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack'
import { createBottomTabNavigator } from 'react-navigation-tabs'

/** Icons: Ionicons */
import { Ionicons } from '@expo/vector-icons'

/** Screens: loading & accounts */
import LoadingScreen from './src/screens/LoadingScreen'
import LoginScreen from './src/screens/LoginScreen'
import RegisterScreen from './src/screens/RegisterScreen'

/** Screens tabs: Trending, Categories, Cart, Location, Profile */
import OffersScreen from './src/screens/OffersScreen'
import CategoriesScreen from './src/screens/CategoriesScreen'
import CartScreen from './src/screens/CartScreen'
import LocationScreen from './src/screens/LocationScreen'
import ProfileScreen from './src/screens/ProfileScreen'

/** Reducers */
import AuthReducers from './src/reducers/AuthReducers'

const AppContainer = createStackNavigator({
    default: createBottomTabNavigator({
      Offers: {
        screen: OffersScreen,
        navigationOptions: {
          tabBarIcon: ({ tintColor }) => <Ionicons name="ios-flash" size={24} color={tintColor} />
        }
      },
      Categories: {
        screen: CategoriesScreen,
        navigationOptions: {
          tabBarIcon: ({ tintColor }) => <Ionicons name="ios-pricetags" size={24} color={tintColor} />
        }
      },
      Cart: {
        screen: CartScreen,
        navigationOptions: {
          tabBarIcon: ({ tintColor }) => (
            <View style={{ backgroundColor: '#E9446A', borderRadius: 100, width: 50, height: 50, marginBottom: 5, alignItems: 'center', justifyContent: 'center', shadowColor: "#454D65", shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }}>
              <Ionicons name="ios-cart" size={30} color="#ffffff" />
            </View>
          )
        }
      },
      Location: {
        screen: LocationScreen,
        navigationOptions: {
          tabBarIcon: ({ tintColor }) => <Ionicons name="ios-pin" size={24} color={tintColor} />
        }
      },
      Profile: {
        screen: ProfileScreen,
        navigationOptions: {
          tabBarIcon: ({ tintColor }) => <Ionicons name="ios-person" size={24} color={tintColor} />
        }
      },
    },
    {
      defaultNavigationOptions: {
        tabBarOnPress: ({ navigation, defaultHandler }) => {
          navigation.state.key === 'Cart' ? navigation.navigate('cartModal') : defaultHandler()
        }
      },
      tabBarOptions: {
        activeTintColor: "#161F3D",
        inactiveTintColor: "#B8BBC4",
        showLabel: false,
      },
    },
  ),
  cartModal: {
    screen: CartScreen
  }
},
{
  mode: 'modal',
  headerMode: 'none',
  // initialRouteName: 'cartModal',
})

const AuthStack = createStackNavigator({
  Login: LoginScreen,
  Register: RegisterScreen,
})

const AppInit = createAppContainer(
  createSwitchNavigator({
    Loading: LoadingScreen,
    App: AppContainer,
    Auth: AuthStack,
  },
  {
    initialRouteName: 'Loading'
  })
)

/** Creando store: auth => para almacenar el login del usuario. */

const rootReducer = combineReducers({
  auth: AuthReducers,
})

const store = createStore(rootReducer, applyMiddleware(ReduxThunk))

/** */

export default class App extends Component {
  constructor(props) {
    super(props)
  }

  componentDidMount() {
    this.loadElements()
  }
  async loadElements() {
    await Font.loadAsync({
      Roboto: require('native-base/Fonts/Roboto.ttf'),
      Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
    })
  }

  render() {
    return (
      <Provider store={store}>
        <Root>
          <AppInit />
        </Root>
      </Provider>
    )
  }
}

react-native run-android freezes on deleting Gradle directory

$
0
0

I'm trying to run a React Native app:

react-native run-android

however when I do so I get these messages:

info Starting JS server...

info Installing the app...

Deleting directory C:\Users\edkol\.gradle\wrapper\dists\gradle-5.4.1-all\3221gyojl5jsh0helicew7rwx\gradle-5.4.1

and the app never runs, even if I have an emulator open prior to running the command.

How do I get the app to run?

Thanks! :)

Accessibility Identifier issue in ReactNative

$
0
0

I am setting accessibility identifier for my components in react native using testID in iOS and accessibilityLabel in android. For iOS is working fine but for Android it my identifier is appended with , (a comma and a space). I am not sure what is causing issue. Here is my code:

const renderAccessibilityLabel = (str) => {
  const propsForAutomation = {};
  if (Platform.OS === "ios") {
    propsForAutomation.testID = str;
  } else {
    propsForAutomation.accessibilityLabel = str;
  }
  return propsForAutomation;
};

// Inside render method:
<Text {...renderAccessibilityLabel("MyText")}>{MyText}</Text>

result > ios: MyText android: MyText,

I don't know whats wrong with code :(

Can I use react-native for developing maps app

$
0
0

I have a question regarding possibility to uses react-native library for developing the app (ios/android) which will able to support to works with google/apple maps [put points, measure distance, etc] So, the main question is react-native good choice for developing the app with this functionality or instead of this I should use native lang such as (swift/java) ? :)

Can we get face-id in react native for Android devices?

$
0
0

I was implementing biometrics in my app for authentication. I am using react-native biometrics for it. Every things working good just one stucked. Face-id is not working in Android. I did a lot of googling but unable to find some satisfactory answer. Is it even possible to use face-id in Android?

Biometrics.isSensorAvailable()
  .then((biometryType) => {
    if (biometryType === Biometrics.TouchID) {
      console.log('TouchID is supported')
    } else if (biometryType === Biometrics.FaceID) {
      console.log('FaceID is supported')
    } else {
      console.log('Biometrics not supported')
    }
  })  

This always return me TouchId even if I am using FaceId in my phone. Thank for help in advance.

Parse React Native photo upload error on android

$
0
0

Uploading a file to Parse backend using react native on IOS works fine, on android it does return an error

import Parse from "parse/react-native";
...    
...

let base64 = cy.state.image;
        let imageFile = new Parse.File("image.png", base64, "image/png");
        imageFile.save().then(
          img=>{
            console.log("......", img)
          }
        )

the result on IOS:

...... Object {
  "__type": "File",
  "name": "fe9e1132894eeca3a6102d6a1e0a567c_image.png",
  "url": "http://SERVER_IP_ADDRESS/parse/app2/files/app2/fe9e1132894eeca3a6102d6a1e0a567c_image.png",
}

the result on Android:

...... Object {
  "__type": "File",
  "name": undefined,
  "url": undefined,
}

Can't build React Native after add React-Native-Camera and Recat-Native-Push-Notification

$
0
0

My existing project was working fine with

"react-native": "0.59.x",
"react-native-camera": "^2.11.2"

After i added "react-native-push-notification" to my project =>

"react-native": "0.59.x",
"react-native-camera": "^2.11.2",
"react-native-push-notification": "^2.1.0",

I encountered several issues, and i fixed them one by one and after add

android.enableJetifier=true
android.useAndroidX=true

to the gradle.properties i ended up with a issue in React-Native-Camera

Execution failed for task ':react-native-camera:compileGeneralDebugJavaWithJavac'

I doubt the error occurred because of some version mismatches, but i couldn't find it. Can someone help me to resolve this issue?


Setting up Detox with Expo on Android

$
0
0

For the last two days, i'm trying to understand how to setting up Detox with Expo for Android. I saw a lot of tutorial to configure it on iOS but not on android.

I saw there is some package to install to be compatible with Expo (like detox-expo-helpers , expo-detox-hooks) but impossible to launch my test on an Android emulator or even my physical mobile.

If someone have already go through this problem, I would to know how to launch my first end to end tests on Android using Expo.

Color of status bar using react navigation

$
0
0

I use React Navigation and I need to set the background color of the status bar darker than header. But Android Emulator has already done this automatically, when my phone set bgColor: none.

If I use component StatusBar with attribute bg, I wont change bg(but I can change barStyle-_-)

Screen of my phone

Screen of Anroid Emulator

View inside MapView, breaks the code in React Native

$
0
0

I am developing a React Native map and I am trying to add a View, inside my MapView, so that I can display the estimated duration and estimated distance towards a given location. But whenever I run my code, I receive a 'The specified child already has a parent. You must call removeView() on the child's parent first'. This is the code inside 'return()':

<MapView
        showsUserLocation
        style = { styles.map }
        customMapStyle = { customMapStyles }
        initialRegion={{
          latitude,
          longitude,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421
        }}
        >
          <View
          style={{
            width,
            paddingTop: 10,
            alignSelf: 'center',
            alignItems: 'center',
            height: height * 0.15,
            backgroundColor: 'white',
            justifyContent: 'flex-end',
           }}
          >
            <Text style = {{ fontWeight: 'bold' }}>
              Estimated Arrival Time: {time}
            </Text>
            <Text style = {{ fontWeight: 'bold' }}>
              Estimated Distance: {distance}
            </Text>
          </View>
          {this.renderMarkers()}
          <MapView.Polyline 
          strokeWidth={2}
          strokeColor="blue"
          coordinates={coords}
          />

          <Image 
          source={{ uri: destination && destination.image_url }}
          style={{
            //height and width are made responsive with dimensions
            flex: 1,
            width: width * 0.95,
            alignSelf: 'center',
            height: height * 0.15,
            position: 'absolute',
            bottom: height * 0.05
           }}
          />

        </MapView>

The code broke right after I added the 'View' right below the 'MapView' declaration. The styles for the MapView are these:

    ...StyleSheet.absoluteFillObject,
    flex: 1,
    height: '60%',

I tried putting them inside a wrapping View and giving that View a 'flex: 1'. Also tried a self-closing MapView tag, but then I receive this error - 'JSX expressions must have one parent element'. I tried giving the View a absolute position, but that also didn't help. Help would be much appreciated, thanks in advance ! If I remove the 'Image' and 'View' tags, the code works perfectly.. I can work without the 'Image' tag since it was added just for testing, but I need the 'View' that displays the distance and arrival time..

Scrollable child on android is not scrollable when in a ScrollView

$
0
0

I'm trying to use react-native-webview in a horizontally scrollable ScrollView.

On IOS it's working fine, but on Android it seems that if the user don't scroll in a perfect vertical manner, the scrollView starts to steal all the events which completely blocks scrolling in the webView.

Again, on IOS it works fine

The code looks a little like this

<ScrollView
  ref={(c) => {this.scroll = c}}
  onMomentumScrollEnd={this.handleScroll}
  horizontal
  pagingEnabled
  showsHorizontalScrollIndicator={false}
  decelerationRate={0.0}
  directionalLockEnabled
  nestedScrollEnabled
>

   <WebView
     style={ webviewStyle }
     source={{ uri: 'http://www.google.com' }}
     startInLoadingState
   />
   <WebView
     style={ webviewStyle }
     source={{ uri: 'http://www.google.com' }}
     startInLoadingState
   />

</ScrollView>



How do I get react-native-calendar-events working on Android platform React-Native 60+?

$
0
0

I was struggling for a couple of weeks to get the react-native-calendar-events library working on my React Native project after it was upgraded from 0.53.3 to 0.60.4.

I was able to get it working on the iOS side via refactoring some code to execute authorizeEventStore before checking authorizationStatus like so:

export async function createCalendarEvent(event) {
  const store = await RNCalendarEvents.authorizeEventStore();
  console.log(store);
  if (store === "authorize") {
    addToCalendar(event);
  } else {
    RNCalendarEvents.authorizationStatus()
      .then(auth => {
        // handle status
        if (auth === "authorized") {
          addToCalendar(event);
        }
      })
      .catch(() => {
        alert("This app needs calendar access");
      });
  }
}

Unfortunately, this does not work on the Android side of the application. I have followed the Android setup guide here, even though it should not apply at this point with React-Native 60+ because of autolinking but I was running out of ideas:

https://github.com/wmcmahan/react-native-calendar-events/wiki/Android-setup

Sure enough, the above implementation did not work and there is no updated documentation. Not sure what I am missing, I have set this up on Android via autolinking, via the implementation above and still nothing.

I have been unsuccessful in getting any response from an open issue with the author of the lib: https://github.com/wmcmahan/react-native-calendar-events/issues/278

On the Android side when JavaScript executes this code:

export async function createCalendarEvent(event) {
  const store = await RNCalendarEvents.authorizeEventStore();
  console.log(store);
  if (store === "authorized") {
    addToCalendar(event);
  } else {
    RNCalendarEvents.authorizationStatus()
      .then(auth => {
        // handle status
        if (auth === "authorized") {
          addToCalendar(event);
        }
      })
      .catch(() => {
        alert("This app needs calendar access");
      });
  }
}

async function addToCalendar(event) {
  try {
    const startDate =
      Platform.OS === "ios"
        ? format(parse(event.StartDateLocal))
        : parse(event.StartDateLocal);
    const endDate =
      Platform.OS === "ios"
        ? format(parse(event.EndDateLocal))
        : parse(event.EndDateLocal);
    const allEvents = await RNCalendarEvents.fetchAllEvents(startDate, endDate);

    const calendarEvent = allEvents.find(e => e.title === event.Title);
    if (calendarEvent) {
      alert("You have already added this event to your calendar.");
    } else {
      const title = event.Title;

      const {
        Location: {
          AddressLine1: address,
          City: city,
          StateAbbreviation: state,
          PostalCode: zip
        }
      } = event;

      const location = `${address}, ${city}, ${state}, ${zip}`;

      const settings = {
        location,
        startDate,
        endDate
      };
      RNCalendarEvents.saveEvent(title, settings)
        .then(() => {
          alert("Event Saved");
        })
        .catch(rejectionReason => {
          console.log(rejectionReason);
          alert("Oops! Something has gone wrong.");
        });
    }
  } catch (e) {
    alert(e.message);
  }
}

it continues to print out alert("Oops! Something has gone wrong."); as opposed to the iOS side which prints out alert("Event Saved");

Viewing all 29678 articles
Browse latest View live


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