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

Does compileOnly work with Android Native Module?

$
0
0

I need a help for android native module. Does compileOnly dependency works in Native module.

Let's say I have two native SDKs com.google.firebase:firebase-messaging and com.google.firebase:firebase-inappmessaging-display and one react native plugin firebase-react-native

In 1 plugin only i want to expose public APIs for both native SDKs but I want to add it as optional dependency(compileOnly) so If few Apps don't want to use com.google.firebase:firebase-messaging then they can omit it in App's gradle file.

In Android world it works easily. But in RN when i add one of them as comipleOnly then it throws ClassNotFoundException during runtime.

How do I achieve optional SDK support for Apps so that extra SDK size does not introduce without creating 2 seprate RN plugins?

Thanks


I have created header component and i want to open drawer from there

$
0
0

I have created header component and i want to open drawer from header component from icon click, currently swipe is opening drawer. please help if anyone know what is the issue

this is my app js code where i created drawer navigator

<NavigationContainer><Drawers.Navigator drawerContent={props => <Drawer {...props} />} ><Drawers.Screen                  name="Home"                  component={Home}                  initialParams={({navigation}) => {                    return{                      headerTitle:() => <HomeHeader navigation={navigation}/>,                    }                  }}              /><Drawers.Screen                name="Orders"                component={Orders}            /><Drawers.Screen                name="Account"                component={Account}            /></Drawers.Navigator></NavigationContainer>

and this is my header component where i was trying to navigation.openDrawer

export default function HomeHeader({navigation}) {    const openMenu = () => {        navigation.openDrawer();    }    return (<View style={GlobalStyle.hheader} ><View style={GlobalStyle.mainMenu} ><Icon type="material" name="menu" size={26} color="black" onPress={openMenu} /></View><View style={GlobalStyle.near} ><Text style={GlobalStyle.nTitle}>Your Location</Text><Text style={GlobalStyle.nLocate}>Mehran Town <Icon   iconStyle={{ marginBottom:-1, }} name='chevron-down' size= {16}  type='font-awesome' color='#000'    /></Text></View></View>    )}

and finally draweritem code

<DrawerItem                         label="Profile"                        onPress={() => {props.navigation.navigate('Account')}}                        labelStyle={{color: '#000', fontSize:15}}                        icon={() => (<Icon                             name='account-circle'                            type='material'                            color='#4285F4'                            size={18}                            />                        )}                    /><DrawerItem                         label="Orders"                        onPress={() => {props.navigation.navigate('Orders')}}                        labelStyle={{color: '#000', fontSize:15}}                        navigation={props.navigation}                        icon={() => (<Icon                             name='receipt'                            type='material-icons'                            color='#4285F4'                            size={18}                            />                        )}                    /></View>

React Native: Background job not executing on some Android OS versions?

$
0
0

I have tried to integrate the following npm packages regarding sending Push Notification:

  • react-native-background-job
  • react-native-background-fetch
  • react-native-background-task

For Push Notifications:

  • react-native-push-notification

The Notifications work fine in the foreground. The problem is that the background service does not run in certain Android OS. Take a look at the following code:

// Importsimport BackgroundJob from 'react-native-background-job';..// Define the Jobconst backgroundJob = {  jobKey: "PNJob",  job = () => {  console.log("Running in Background!");  // Execute Push Notification  }};// Register Background JobBackgroundJob.register(backgroundJob);var backgroundSchedule = {  jobKey: "PNJob",  period: 1800000, // Interval every half Hour (in ms)  timeout: 5000,  requiresCharging: false,  override: true,  persist: true,  // allowExecutionInForeground: true,  allowWhileIdle: true,  requiresDeviceIdle: false,  // exact: true};// ***  Schedule  ***BackgroundJob.schedule(backgroundSchedule)  .then(() => console.log("The Job has been scheduled!"))  .catch(() => console.log("There was a problem in scheduling"));

I've tried debugging several possible issues but there is still some underlying issue I can not place.

Malformed calls from JS : field sizes are different [[8,39],[4,0]

$
0
0

I want to display the list of contacts on my AVD but Im facing an error (I tried linking the package but it did nothing):

My code :

    const [contact, setContact] = useState([]);    useEffect(() => {      PermissionsAndroid.request(        PermissionsAndroid.PERMISSIONS.READ_CONTACTS,        {'title': 'Contacts','message': 'This app would like to view your contacts.'        }      ).then(() => {        Contacts.getAll((err, contacts) => {          if (err === 'denied'){            // error          } else {            // contacts returned in Array            setContact(contacts);            console.log(contact);          }        })      })      .catch((err)=> {          console.log(err);      })    }, []);

The error :

enter image description here

I searched everywhere for a solution but there's nothing about this issue, thanks for helping me by advance.

ScrollView programmatically scroll on button press in react native

$
0
0

So I manually created an onboarding screen in React Native using ScrollView and also I added a button labeled next to enable the hidden screen to move in on the screen, Now my challenge is how I can programmatically make my ScrollView Scroll when the button is pressed. Below is my sample functional component I tried my hand at, but I have no idea how I'll go about implementing the button press scroll

export default function Onbaording({ navigation }) {  const [sliderState, setSliderState] = React.useState({ currentPage: 0 });  const { width, height } = Dimensions.get("window");  const setSliderPage = (event) => {    const { currentPage } = sliderState;    const { x } = event.nativeEvent.contentOffset;    const indexOfNextScreen = Math.floor(x / width);    if (indexOfNextScreen !== currentPage) {      setSliderState({        ...sliderState,        currentPage: indexOfNextScreen,      });    }  };  const { currentPage: pageIndex } = sliderState;  return (<View style={Styles.container}><SafeAreaView style={{ flex: 4 }}><ScrollView          horizontal={true}          scrollEventThrottle={16}          pagingEnabled={true}          showsHorizontalScrollIndicator={false}          snapToStart={true}          onScroll={(event: any) => {            setSliderPage(event);          }}><View style={{ width, height, paddingHorizontal: 16 }}><View style={Styles.Svg}><WelcomeSvg1 /></View><Text style={Styles.text}>Onboarding</Text><Text>              Done with React Native.</Text></View><View style={{ width, paddingHorizontal: 16 }}><View style={Styles.Svg}><WelcomeSvg2 /></View><Text style={Styles.text}>Onboarding</Text><Text>              Done with React Native.</Text></View></ScrollView><View style={Styles.paginationWrapper}>            {Array.from(Array(2).keys()).map((key, index) => (<View                style={[                  Styles.paginationDots,                  {                    backgroundColor:                      pageIndex === index ? "#51668F" : "#EAEAEA",                  },                ]}                key={index}              />            ))}</View></SafeAreaView><View><View            style={{ flexDirection: "row", justifyContent: "space-between" }}><TouchableOpacity              onPress={() => {                navigation.navigate("Signin");              }}><Text>Skip</Text></TouchableOpacity><TouchableOpacity><Text>Next</Text></TouchableOpacity></View></View></View>  );}

How to implement mobile device management using react native?

$
0
0

I am developing an application for internal use that allows a mobile administrator to configure and install applications from a local repository, like a play store or apple store but for applications distributed locally.This application has to allow an administrator to disable/enable some features of the phone also, like access to the phone settings.

I'm currently able to install and configure applications, but I don't know what npm package to use for the administration of the system settings, wherever I look they say that third party application can't mess around with the system settings unless the device is rooted.There is an npm package that allows to change settings one by one, but can't disable the home button, disable interaction with the notification panel, nor disable access to the phone settings.

Any direction would be appreciated.

How to fix TypeError: Network request failed at EventTarget.xhr.onerror (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false

$
0
0

TypeError: Network request failed at EventTarget.xhr.onerror (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false

I'm using fetch API post call from react native app to chargebee Node tab for creating new customer and getting JSON response error message on android.

The error message

The code:

   chargebee.configure({"{site}",api_key : "{site_api_key}"})             chargebee.customer.create({             first_name : "John",             last_name : "Doe",             email : "john@test.com",             locale : "fr-CA",             billing_address : {             first_name : "John",             last_name : "Doe",             line1 : "PO Box 9999",             city : "Walnut",             state : "California",             zip : "91789",             country : "US"             }             }).request(function(error,result) {             if(error){             //handle error             console.log(error);             }else{              console.log(result);             var customer = result.customer;             var card = result.card;             }             });

The error in image is coming from handle error console.log(error);

React Native Link for React Native .60 +

$
0
0

This is still something that is required, I see this message all the time, but it's completely invalid from what I have experienced. Almost every package I work with, I still have to run the react-native link.

enter image description here

Can anyone tell me what's up with this? Is it just particular packages, or why do I still need to run react-native link all the time, when it tells me I shouldn't run it. I mean, it's really just adding it to the pod file for iOS and gradle for Android.

Anyone else experiencing this?

To show this further, look at this, just ran the npm install for lottie, it will not work unless I run the link, should I add to my pod file manually? I don't get why React Native (Facebook) team is saying that it's no longer required, out of our team of 4 people, we have had it required always.

enter image description here


gradle: Could not find method setIgnore()

$
0
0

https://developer.android.com/studio/build/build-variants

The file says that setIgnore() can filter the configuration.

But when I use it, the following error is prompted:

 org.gradle.internal.metaobject.AbstractDynamicObject$CustomMessageMissingMethodException: Could not find method setIgnore() for arguments [true] on object of type com.android.build.gradle.internal.api.ApplicationVariantImpl
  variantFilter { variant ->      def names = variant.flavors*.name      // To check for a certain build type, use variant.buildType.name == "<buildType>"      if (names.contains("minApi21") && names.contains("demo")) {          // Gradle ignores any variants that satisfy the conditions above.          setIgnore(true)      }  }

How can I fix it?

Android Barcode Scanner Module

$
0
0

I have a Barcode Scanner peripheral attached to my phone (see attached image) and cannot seem to find a way to access the readings of the scanner. The phone is reading the barcodes as there is an emulator app within the phone which displays the numeric values of barcodes once scanned.

My question is, how can the Barcode peripheral be accessed? Similar to how the Camera is accessed via the NPM package RNCamera (React Native).

Phone

React-Native: 'List of devices attached' not showing any device. Also, 'Could not get BatchedBridged' issue

$
0
0

Description

Hi, I'm new to the react-native platform. I followed all the steps given here: react-native getting-started, to setup my development environment.

Details

  • React Native version: 0.42
  • Platform I want to work for: Android
  • Operating System: Linux (Ubuntu 16.04.1 LTS 64-bit)
  • Phone: OnePlus 2 - AndroidVersion 6.0.1 - Marshmallow

I followed these steps: running-on-device, to run the app on my phone connected to my laptop via USB cable. I've enabled debugging over USB and inserted device id in udev rules with the process mentioned.

Now when I run $ adb devicesIt lists no android device attached. Here's how it looks:

enter image description here

Also, when I run $ react-native run-androidthen my phone shows these messages:

enter image description here

enter image description here

Being totally new to the platform, I really need help. Can someone please explain what could be wrong here. Thanks

How do you Update major React native Versions (eg. 0.61.5 to 63.4)

$
0
0

I am already familiar with this website react native helper but so far I was unable to do this without failure and headache as some files in ios and android projects are binary like and its not possible to do it efficiently for example .pbxproj files.

is there a way we can use git diff to replace legacy codes or any good way to update major versions?

how to get file path from intent data uri

$
0
0

I'm using intent to select a video,

fun openVideo(view: View) {        val intent = Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)        intent.type = "video/*"        startActivityForResult(            Intent.createChooser(intent, "Select Video"),            REQUEST_TAKE_GALLERY_VIDEO        )}

then i'm getting uri and path

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {        super.onActivityResult(requestCode, resultCode, data)        if (requestCode == REQUEST_TAKE_GALLERY_VIDEO && data != null) {            val videPath = data.data?.path             val selectedVideoUri: Uri? = data!!.data.toString()        }    }

output

videPath:/external_files/KannadaGeeta/05CHAPTER2.mp3selectedVideoUri :content://com.mi.android.globalFileexplorer.myprovider/external_files/KannadaGeeta/05CHAPTER2.mp3

but I need path like below to check whether file exist or not

/storage/emulated/0/KannadaGeeta/13CHAPTER12.mp3

Look, by working on strings I can achieve what I want. But I'm looking for a proper way to get the video path.

Can anyone help me on this.

Edit:

i tried this which is giving false

File(selectedVideoUri).exists()

Invisible Recaptchav3: How to get Error Callback in React Native

$
0
0

I'm struggling with Invisible Recaptcha v3 by Google. I've implemented it and it works fine, but I haven't been able to find a way in case recaptcha fails due to network issue etc...

I've implemented it as follows:

import React from "react";import { StyleSheet, View } from "react-native";import { WebView } from "react-native-webview";import { platform } from "./constants";type IProps = {  captchaDomain: string;  onReceiveToken: (captchaToken: string, callback?: Function) => void;  siteKey: string;};const patchPostMessageJsCode = `(${String(function() {  const originalPostMessage = window.postMessage;  const patchedPostMessage = (    message: any,    targetOrigin: any,    transfer: any  ) => {    originalPostMessage(message, targetOrigin, transfer);  };  patchedPostMessage.toString = () =>    String(Object.hasOwnProperty).replace("hasOwnProperty", "postMessage");  window.postMessage = patchedPostMessage;})})();`;const getExecutionFunction = (siteKey: string) => {  return `window.grecaptcha.execute('${siteKey}', { action: 'login' }).then(    function(args) {      window.ReactNativeWebView.postMessage(args);    }  )`;};const getInvisibleRecaptchaContent = (siteKey: string) => {  return `<!DOCTYPE html><html><head><script src="https://www.google.com/recaptcha/api.js?render=${siteKey}" onerror="onErrorCallback()"></script><script>window.grecaptcha.ready(function() { ${getExecutionFunction(      siteKey    )} });</script></head></html>`;};class ReCaptchaComponent extends React.Component<IProps> {  private _webViewRef = React.createRef<WebView>();  private _callbackFunction?: Function;  public refreshToken(onReceiveCallback?: Function) {    const { siteKey } = this.props;    this._callbackFunction = onReceiveCallback;    if (platform.isIOS && this._webViewRef.current) {      this._webViewRef.current.injectJavaScript(getExecutionFunction(siteKey));    } else if (platform.isAndroid && this._webViewRef.current) {      this._webViewRef.current.reload();    }  }  render() {    const { captchaDomain, onReceiveToken, siteKey } = this.props;    return (<View style={styles.webViewContainer}><WebView          ref={this._webViewRef}          style={styles.webView}          javaScriptEnabled          originWhitelist={["*"]}          automaticallyAdjustContentInsets={false}          mixedContentMode="always"          injectedJavaScript={patchPostMessageJsCode}          source={{            html: getInvisibleRecaptchaContent(siteKey),            baseUrl: captchaDomain,          }}          onMessage={(e: any) => {            console.log(`${JSON.stringify(e.nativeEvent.data)}`);            // if (onReceiveToken) {            //   onReceiveToken(e.nativeEvent.data, this._callbackFunction);            // }          }}        /></View>    );  }}const styles = StyleSheet.create({  webViewContainer: { height: 50, overflow: "hidden", opacity: 0 },  webView: { width: 50, height: 50, overflow: "hidden", opacity: 0.9 },});export default ReCaptchaComponent;

I haven't been able to get an error callback in case something goes wrong. I tried .catch but it didn't work:

const getExecutionFunction = (siteKey: string) => {  return `window.grecaptcha.execute('${siteKey}', { action: 'login' }).then(    function(args) {      window.ReactNativeWebView.postMessage(args);    }  ).catch(function(args) {      window.ReactNativeWebView.postMessage(args);    })`;};

Am I missing something here ?

TypeError: Cannot destructure property `stat` of 'undefined' or 'null'

$
0
0

I am getting a TypeError when init new react native project on mac.

I tried

'''react-native init MyProject'''

Project folder was created and inside project folder json file only created


React Native Android zIndex elevation without rearranging

$
0
0

I've got an app with a scrollview with a stickyHeaderIndices prop - applied to a text input. In iOS, the elements are arranged according to zIndex and arrangement. However, on Android the text input hides behind other elements arranged deeper down the code with elevation applied, see this video for reference.

It seems the solution is arranging the text input deeper down the code, but then the text input isn't positioned right. Changing the zIndex, disabling the elevation, disabling absolute positioning and giving the text input a higher elevation value also doesn't change the layering. Brief styling for the text input:

  search: {    zIndex: 100,    position: "absolute",    top: -16,    elevation: 9,    paddingVertical: 12,    alignSelf: "center",  }

Brief styling for the tiles which cover the text input:

tile: {    backgroundColor: colors.white,    padding: 16,    elevation: 8,    zIndex: -5,  },

Is there any way to prevent the textinput from hiding behind the tiles? If any additional code references are needed please let me know.

Drawsana Like library in react native

$
0
0

Iam working on a react native app. I have to implement a drawing feature that allows to draw on things - mark up images with text, shapes, etc. Do we have any library in react native or android that is like Drawsana(https://github.com/Asana/Drawsana) in ios. Any help will be appreciated.

React Native debug with Visual Studio Code not working

$
0
0



i'm trying to use React Native with Visual Studio Code (which should be the best one) but it gives me an error when I try to debug.
I have installed the React Native Tools extension but when I try to start (F5) it returns "[Error] Could not debug. Sure that the reactive-native npm package is installed at the root? "
I also tried sending the command with F1 "> React Native: Run Android" but it returns error "Current workspace is not a React Native project."

I'm using Ubuntu 16.04 LTS.
Visual Studio Code 1.11.2
react-native-cli: 2.0.1
react-native: 0.43.3

Does any of you use Visual Studio Code? Do you have these problems?

My launch.json (the only file generated from extension React Native Tools)

{"version": "0.2.0","configurations": [        {"name": "Debug Android","program": "${workspaceRoot}/.vscode/launchReactNative.js","type": "reactnative","request": "launch","platform": "android","sourceMaps": true,"outDir": "${workspaceRoot}/.vscode/.react"        },        {"name": "Debug iOS","program": "${workspaceRoot}/.vscode/launchReactNative.js","type": "reactnative","request": "launch","platform": "ios","target": "iPhone 5s","sourceMaps": true,"outDir": "${workspaceRoot}/.vscode/.react"        },        {"name": "Attach to packager","program": "${workspaceRoot}/.vscode/launchReactNative.js","type": "reactnative","request": "attach","sourceMaps": true,"outDir": "${workspaceRoot}/.vscode/.react"        },        {"name": "Debug in Exponent","program": "${workspaceRoot}/.vscode/launchReactNative.js","type": "reactnative","request": "launch","platform": "exponent","sourceMaps": true,"outDir": "${workspaceRoot}/.vscode/.react"        }    ]}

Stuck on IDLE status on command promt while running react native (cli) app

$
0
0

I am using react native cli approach for development. Requirements for setting environment are already fulfilled. After running this command npx react-native run-android android emulator launches and following errors occur.

  1. Starting a Gradle Daemon (subsequent builds will be faster)File C:\Users\mycomputer.android\repositories.cfg could not be loaded.

  2. "Install Android SDK Build-Tools 28.0.3 (revision: 28.0.3)" failed.Checking the license for package Android SDK Platform 29 in C:\Users\mycomputer\AppData\Local\Android\Sdk\licensesLicense for package Android SDK Platform 29 accepted.Preparing "Install Android SDK Platform 29 (revision: 5)".<=============> 100% CONFIGURING [14m 12s] > IDLE

Cannot read property 'getContactsAsync' of undefined, expo-contacts, ANDROID

$
0
0

On my expo ejected project, im trying to use expo-contacts with no success.

"react-native": "~0.61.5",

"expo": "~37.0.3",

i ran expo install expo-contacts

import * as Permissions from 'expo-permissions';import * as Contacts from 'expo-contacts'; getContact = async () => {    try {      let { status } = await Permissions.askAsync(Permissions.CONTACTS);        if (status === 'granted') {          const { data } = await Contacts.getContactsAsync({            fields: [Contacts.Fields.Emails],          });          console.log("getContact / data: ", data);          if (data.length > 0) {            const contact = data[0];            console.log("getContact / contact: ", contact);          }        }    } catch(e){      console.log("getContact / error: ", e)    }  }

enter image description here

Viewing all 29631 articles
Browse latest View live


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