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

react-native How to open local file url using Linking?

$
0
0

I'm using the following code to download a file (can be a PDF or a DOC) and then opening it using Linking.

const { dirs } = RNFetchBlob.fs;let config = {    fileCache : true,    appendExt : extension,    addAndroidDownloads : {        useDownloadManager : false,        notification : false,        title : 'File',        description : 'A file.',        path: `${dirs.DownloadDir}/file.${extension}`,    },};RNFetchBlob.config(config)    .fetch(        method,        remoteUrl,        APIHelpers.getDefaultHeaders()    )    .then((res) => {        let status = res.info().status;        if (status == 200) {            Linking.canOpenURL(res.path())                .then((supported) => {                    if (!supported) {                        alert('Can\'t handle url: '+ res.path());                    } else {                        Linking.openURL(res.path())                            .catch((err) => alert('An error occurred while opening the file. '+ err));                    }                })                .catch((err) => alert('The file cannot be opened. '+ err));        } else {            alert('File was not found.')        }    })    .catch((errorMessage, statusCode) => {        alert('There was some error while downloading the file. '+ errorMessage);    });

However, I'm getting the following error:

An error occurred while opening the file. Error: Unable to open URL:file:///Users/abhishekpokhriyal/Library/Developer/CoreSimulator/Devices/3E2A9C16-0222-40A6-8C1C-EC174B6EE9E8/data/Containers/Data/Application/A37B9D69-583D-4DC8-94B2-0F4AF8272310/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_o259xexg7axbwq3fh6f4.pdf

I need to implement the solution for both iOS and Android.


Button click to show another page without navigation using react native

$
0
0

In my scenario, I am having separate class for example page1, page2 and page3. Here, I need to call Page1 button click to Page 2 without navigation the transition like sudden appear popup screen. How to achieve this?

Below code I am using,

<TouchableOpacity              onPress={() => {         // Here I need to call Page 2              }}>

How can I navigate the activity to another activity in react native in a simple way?

$
0
0

I am trying to navigate my first page to the second page by tapping a button.Once we are at the second page, we will never go back by pressing back button.

Just tap, switch, and never go back.

Is there any simple way to do this? I mean, I just don't want to use the component Navigation or Navigator. They are too complex.

react-native-video example throws "TypeError:undefined" error

$
0
0

I'm very new with react native. I'm trying to make an app that has a youtube video embeded.I'm trying the example of this repo but it crashes on my project.

here is my full code. Crashes are comented where they are thrown. I dont understand what I'm doing wrong.

I'm using webstorm and I'm pretty sure that i've installed the package and linked it using thoose commands:

npm install --save react-native-video

react-native link react-native-video

import React from 'react';import {  SafeAreaView,  StyleSheet,  ScrollView,  View,  Text,  StatusBar,} from 'react-native';import {  Header,  LearnMoreLinks,  Colors,  DebugInstructions,  ReloadInstructions,} from 'react-native/Libraries/NewAppScreen';import Video from 'react-native-video';const App: () => React$Node = () => {  return (<><StatusBar barStyle="dark-content" /><SafeAreaView><ScrollView          contentInsetAdjustmentBehavior="automatic"          style={styles.scrollView}><View style={styles.body}><View><Video source={{uri: "https://www.youtube.com/watch?v=83mkGuGLNZg"}}                 ref={(ref) => {                   this.player = ref //Crash with TypeError:undefined is not an object                 }}                                      // Store reference                 onBuffer={this.onBuffer}                //Crash with TypeError:undefined is not an object                 onError={this.videoError}               //Crash with TypeError:undefined is not an object                 style={styles.backgroundVideo}              /></View></View></ScrollView></SafeAreaView></>  );};const styles = StyleSheet.create({  scrollView: {    backgroundColor: Colors.lighter,  },  engine: {    position: 'absolute',    right: 0,  },  body: {    backgroundColor: Colors.white,  },  sectionContainer: {    marginTop: 32,    paddingHorizontal: 24,  },  sectionTitle: {    fontSize: 24,    fontWeight: '600',    color: Colors.black,  },  sectionDescription: {    marginTop: 8,    fontSize: 18,    fontWeight: '400',    color: Colors.dark,  },  highlight: {    fontWeight: '700',  },  footer: {    color: Colors.dark,    fontSize: 12,    fontWeight: '600',    padding: 4,    paddingRight: 12,    textAlign: 'right',  },  backgroundVideo: {    position: 'absolute',    top: 0,    left: 0,    bottom: 0,    right: 0,  },});export default App;

Stop loading Webview in react native

$
0
0

I have react native project on Android platform.I have a Webview loaded from url. When user click any url, i want navigate to screen in my app and webview will stop loading. So in my onNavigationStateChange() function

  source = {{uri:this.props.htmlUrl}}    ref='_webView'    scrollEnabled={true}    javaScriptEnabled={true}    domStorageEnabled={true}    onNavigationStateChange ={(navState)=>{      //handle navigate another screen       this.refs._webView.stopLoading();    }}

It works. So when i go back, and click other url, I can not touch any url in webview.If someone meet the same issue, please help me. Thanks in advance.

Running a Foreground Service in React Native

$
0
0

We're working on a React Native app that scans user WiFi routers repeatedly.

TL;DR:We can't operate a Foreground Service on React Native. We'd like to see an example of a project who did it.

Due to several Google restrictions, we are only able to scan routers at each 30 seconds in average. This is enough for us.The problem appears when the app goes to Background. On this case Google restricts all apps to scan at a minimum interval of 30 minutes which is just not enough for us.

That's why we decided our best way to handle the situation is make the app always work as a Foreground Service which allows to work with foreground limitations even on background.

Note: For now, we ignore possible battery draining situation as we prioritize performance.

To make the app always be on Foreground we have been trying to activate a Foreground Service, but just couldn't succeed. We couldn't even log a message while on background, not to mention running the whole app.

We tried:

We are ready to write java code as well, but we just want to make sure it's even possible as it will require much development time.We'd like to see a working example project in React Native :)Thanks in advance!

How to show overlay page using react native for iOS and android?

$
0
0

In my code, I am having two screens with two different class files. Here, I need to do screen one button click to show screen two. Screen two need to show like a overlay screen and if screen two button click then it should dissolve and back to screen one. how to achieve this?

sample screen enter image description here

below code I am using for click to call another page

<TouchableOpacity              onPress={() => {                this.setState({ isVisible: false });                this.props.navigation.navigate('screen2');              }}>

How to link packages in react-native

$
0
0

I am getting these errors while running my app.

"""bundling failed: Error: Unable to resolve module react-native-screens from node_modules/react-navigation-tabs/src/navigators/createBottomTabNavigator.js"""

How to solve this error. I just reinstalled the node modules and again installed the modules. Can someone help?


How to restrict android app for tablet/handset using expo?

$
0
0

I have separate APKs for the same app. For tablets and for handsets.Also I'm using expo in my project.Due to android documentation I should declare <supports-screens> in <manifest> like this for tablet support only:

<manifest ... ><supports-screens android:smallScreens="false"                      android:normalScreens="false"                      android:largeScreens="true"                      android:xlargeScreens="true"/></manifest>

But it's not good solution, because eject is necessary.How can solve my problem without expo eject ?

React Native: Retrieve data from content uri like content://mms

$
0
0

I create an android app (only) with React Native and i need to get the complete list of MMS.

By searching in some libraries, i found that we can in Java (or Kotlin) get list of SMS by calling this uri: 'content://sms'.

Question: Is there any lib to fetch data from uri like 'content://mms' (or anything like 'content://') in React Native ?

I tried to use 'react-native-fs', but nothing found !

CI/CD BitRise React Native Android Build Failing

$
0
0

Facing issue while build on BitRise.io

I have a React Native Project which builds successfully on local.Using BitRise.io for CI CD.Added App and provided all the essential information and keystore file as well.Followed their getting started guide and everything they'll need is in place.

Tried to build multiple times but getting this error :

Failed to open project, error: no build.gradle or build.gradle.kts file found in (/Users/vagrant/git)| x | android-build@0 (exit code: 1)

format_version: '8'default_step_lib_source: https://github.com/bitrise-io/bitrise-steplib.gitproject_type: react-nativetrigger_map:- push_branch: "*"  workflow: primary- pull_request_source_branch: "*"  workflow: primaryworkflows:  deploy:    steps:    - android-build@0.10.0:        inputs:        - project_location: "$PROJECT_LOCATION"  primary:    steps:    - activate-ssh-key@4.0.3:        run_if: '{{getenv "SSH_RSA_PRIVATE_KEY" | ne ""}}'    - git-clone@4.0.17: {}    - script@1.1.5:        title: Do anything with Script step    - npm@1.1.0:        inputs:        - command: install    - install-missing-android-tools@2.3.7:        inputs:        - gradlew_path: "$PROJECT_LOCATION/gradlew"    - android-build@0: {}    - sign-apk@1: {}    - deploy-to-bitrise-io@1.9.2: {}app:  envs:  - opts:      is_expand: false    PROJECT_LOCATION: android  - opts:      is_expand: false    MODULE: app  - opts:      is_expand: false    VARIANT: release  - opts:      is_expand: false    BITRISE_PROJECT_PATH: ios/sekuraRN.xcworkspace  - opts:      is_expand: false    BITRISE_SCHEME: sekuraRN  - opts:      is_expand: false    BITRISE_EXPORT_METHOD: ad-hoc

Not sure why they are not able to find build.gradle.

ChatService not working on app-release.apk

$
0
0

I have a chatService class in my app which works well when in debug mode but doesn't work at all when i release the app-release apk.

My chat component file looks like this

import React from 'react';import {connect} from 'react-redux';import {  GiftedChat,  Send,  Bubble,  Time,  Composer,} from 'react-native-gifted-chat';import ChatService from '../services/chatService';const TIMEOUT = 10000;class Chatbox extends React.Component {  constructor(props) {    super(props);    this.renderChatMessage = this.renderChatMessage.bind(this);    this.renderEarlierMessages = this.renderEarlierMessages.bind(this);    this.receiveChatMessage = this.receiveChatMessage.bind(this);    this.loadEarlier = this.loadEarlier.bind(this);    this.setChannelFailed = this.setChannelFailed.bind(this);    this.chatService = ChatService(      this.props.auth.token,      this.props.auth.roomToken,      this.receiveChatMessage,      this.renderChatMessage,      this.renderEarlierMessages,    );  }  componentWillUnmount() {    this.chatService.close();  }  componentDidMount() {    this.chatService.open();  }  setChannelFailed() {    this.props.setChannelFailed();  }  // renderOnlineUsers(presence) {  //   presence.list((id, { metas: [first, ...rest] }) => {  //     let count = rest.length + 1;  //   });  // }  receiveChatMessage(messages) {    const userUUID = this.props.currentUser.uuid;    let reciveObj = _.map(messages, (value, key) => {      return {        _id: value.id,        text: value.message,        createdAt: value.inserted_at,        user: {          _id: value.user.uuid,          name: value.user.name,        },      };    });    const message = reciveObj[0];    if (message.user._id !== userUUID) {      this.props.appendMessage(message);    }  }  renderChatMessage(messages) {    let newMessages = _.map(messages.messages, (value, key) => {      return {        _id: value.id,        text: value.message,        createdAt: value.inserted_at,        user: {          _id: value.user.uuid,          name: value.user.name,        },      };    });    if (newMessages.length > 0) {      const lastMessage = newMessages[newMessages.length - 1];      if (newMessages.length < 30) {        this.props.setLoadMore(false);      } else {        this.props.setLoadMore(true);      }      this.props.setMessages(newMessages);      this.props.setLastMessage(lastMessage._id);    }  }  loadEarlier() {    const {lastMessageId} = this.props.socket;    this.chatService.loadEarlier(lastMessageId);  }  renderEarlierMessages(messages) {    let newMessages = _.map(messages.messages, (value, key) => {      return {        _id: value.id,        text: value.message,        createdAt: value.inserted_at,        user: {          _id: value.user.uuid,          name: value.user.name,        },      };    });    const lastMessage = newMessages[newMessages.length - 1];    if (newMessages.length < 30) {      this.props.setLoadMore(false);    } else {      this.props.setLoadMore(true);    }    this.props.setEarlierMessages(newMessages);    this.props.setLastMessage(lastMessage._id);  }  onSend(messages) {    let newMessage = messages[0];    this.props.appendMessage(newMessage);    GiftedChat.append(messages);    this.chatService.send(messages);    analytics.track('Messages Sent', {      messages: messages,    });  }  // draw our ui  render() {    const userUUID = this.props.currentUser.uuid;    const userName = this.props.currentUser.name;    const {loadMore} = this.props.socket;    const {token, roomToken} = this.props.auth;    if (token === null || roomToken === null) {      return (<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}><Image            style={{width: 300, height: 300, resizeMode: 'contain'}}            source={require('../assets/images/error.png')}          /></View>      );    } else {      return (<KeyboardAvoidingView          style={{flex: 1, paddingTop: 0}}          keyboardVerticalOffset="-210"          behavior="padding"          enabled><GiftedChat            scrollToTop            loadEarlier={loadMore}            isTyping={true}            onLoadEarlier={this.loadEarlier}            messages={this.props.messages}            user={{              _id: userUUID,            }}            onSend={messages => {              messages.forEach(element => {                element.user = {                  _id: userUUID,                  name: userName,                };              });              this.onSend(messages);            }}            maxHeight={300}            renderBubble={props => {              return (<Bubble                  {...props}                  textStyle={{                    right: {                      color: '#fff',                      fontFamily: 'Font-Regular',                    },                    left: {                      color: '#fff',                      fontFamily: 'Font-Regular',                    },                  }}                  wrapperStyle={{                    right: {                      backgroundColor: '#5BC388',                      borderTopLeftRadius: 5,                      borderBottomLeftRadius: 5,                      borderBottomRightRadius: 0,                      marginBottom: 5,                      paddingRight: 10,                      paddingBottom:5,                      minWidth: 100,                    },                    left: {                      backgroundColor: '#292C35',                      borderTopRightRadius: 5,                      borderBottomRightRadius: 5,                      borderBottomLeftRadius: 0,                      marginBottom: 5,                      paddingLeft: 10,                      paddingBottom:5,                      minWidth: 100,                    },                  }}                />              );            }}            renderLoading={() => {              return (<ActivityIndicator                  style={{marginTop: 10, paddingTop: 50}}                  size="large"                />              );            }}            // renderComposer={props => {            //   return (            //     <Composer            //       {...props}            //       style={{backgroundColor: '#121519'}}            //       placeholderTextColor="#fff"            //       textInputStyle={{            //         backgroundColor: '#121519',            //         marginLeft: 0,            //         marginTop: 0,            //         height: 50,            //         color: '#fff',            //       }}>            //       <View style={{backgroundColor: '#121519'}} />            //     </Composer>            //   );            // }}            renderSend={props => {              return (<Send {...props}><View                    style={{                      marginRight: 0,                      marginBottom: 0,                      height: 44,                      width: 60,                      //backgroundColor: '#121519',                      alignItems: 'center',                      justifyContent: 'center',                    }}><Text                      style={{                        color: '#5BC388',                        fontSize: 14,                        fontFamily: 'Font-SemiBold',                      }}>                      Send</Text></View></Send>              );            }}            renderTime={props => {              let time = null;              const {currentMessage} = props;              if (!currentMessage.createdAt.getTime) {                let utcTIme = '';                utcTIme = currentMessage.createdAt +'.000Z';                time = new Date(utcTIme);              }              return (<Moment                  style={{fontSize: 12, color: '#fff', paddingHorizontal: 5}}                  utcOffset="+05:30"                  format="HH:mm A"                  element={Text}                  local>                  {currentMessage.createdAt}</Moment>                // <Text                //   style={{                //     marginLeft: "auto",                //     marginLeft: "auto",                //     color: "#cecece"                //   }}                // >                //   {time                //     ? time.toLocaleString("en-IN", {                //         hour: "numeric",                //         minute: "numeric",                //         hour12: true                //       })                //     : currentMessage.createdAt.toLocaleString("en-IN", {                //         hour: "numeric",                //         minute: "numeric",                //         hour12: true                //       })}                // </Text>              );            }}            renderUsernameOnMessage={true}          /></KeyboardAvoidingView>      );    }  }}export default connect(  MapStateToProps,  mapDispatchToProps,)(Chatbox);

and my ChatService looks like this

import { Socket } from '../components/sockets/phoenix'import getEnvVars from "../../environment";const TIMEOUT = 10000const URL = `ws://${PHOENIX_HOST}/socket`;export default (token, roomToken, receiveChatMessage, renderChatMessage, renderEarlierMessages) => {  // construct a socket  const LOBBY = `team_room:${roomToken}`;  const topicId = LOBBY.split(":").slice(-1)[0];  const socket = new Socket(URL, {    params: {      token: token    }  })  // configure the event handlers  socket.onOpen(event => console.log('Connected.'))  socket.onError(event => console.log('Cannot connect.'))  socket.onClose(event => console.log('Goodbye.'))  // open a connection to the server  socket.connect()  // configure a channel into a room - https://www.youtube.com/watch?v=vWFX4ylV_ko  const chan = socket.channel(LOBBY, {})  // join the channel and listen for admittance  chan.join()    .receive('ignore', () => console.log('Access denied.'))    .receive("ok", (msg) => renderChatMessage(msg))    .receive('timeout', () => console.log('Must be a MongoDB.'))  // add some channel-level event handlers  chan.onError(event => console.log('Channel blew up.'))  chan.onClose(event => console.log('Channel closed.'))  // when we receive a new chat message, just trigger the appropriate callback  chan.on(`messages:${topicId}:new`, msg => {    receiveChatMessage(msg)  });  // you can can listen to multiple types  chan.on('user:entered', msg => console.log('say hello to ', msg))  // a function to shut it all down  const close = () => socket.disconnect();  const open = () => socket.connect();  // a function to send a message  const send = (messages) => {    let newMessage = messages[0];    chan      .push("message:add", { message: newMessage.text }, TIMEOUT)      .receive("ok", ({ messages }) => {        analytics.track("Messages Sent", {          messages: messages        });      })      .receive("error", reasons => console.log("flop", reasons))      .receive("timeout", () => console.log("slow much?"));  }  const loadEarlier = (lastMessageId) => {    chan    .push("message:load_more", {      last_message_id: lastMessageId    })    .receive("ok", response => {      renderEarlierMessages(response);    });  }  // reveal a couple ways to drive this bus  return { open, close, send, loadEarlier }}

when in release mode the socket doesn't connect at all.

I'm not using proguard so I don't know whats wrong

my app level build.gradle looks like this

apply plugin: "com.android.application"import com.android.build.OutputFile/** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ *   // the name of the generated asset file containing your JS bundle *   bundleAssetName: "index.android.bundle", * *   // the entry file for bundle generation *   entryFile: "index.android.js", * *   // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format *   bundleCommand: "ram-bundle", * *   // whether to bundle JS and assets in debug mode *   bundleInDebug: false, * *   // whether to bundle JS and assets in release mode *   bundleInRelease: true, * *   // whether to bundle JS and assets in another build variant (if configured). *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants *   // The configuration property can be in the following formats *   //         'bundleIn${productFlavor}${buildType}' *   //         'bundleIn${buildType}' *   // bundleInFreeDebug: true, *   // bundleInPaidRelease: true, *   // bundleInBeta: true, * *   // whether to disable dev mode in custom build variants (by default only disabled in release) *   // for example: to disable dev mode in the staging build type (if configured) *   devDisabledInStaging: true, *   // The configuration property can be in the following formats *   //         'devDisabledIn${productFlavor}${buildType}' *   //         'devDisabledIn${buildType}' * *   // the root of your project, i.e. where "package.json" lives *   root: "../../", * *   // where to put the JS bundle asset in debug mode *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * *   // where to put the JS bundle asset in release mode *   jsBundleDirRelease: "$buildDir/intermediates/assets/release", * *   // where to put drawable resources / React Native assets, e.g. the ones you use via *   // require('./image.png')), in debug mode *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * *   // where to put drawable resources / React Native assets, e.g. the ones you use via *   // require('./image.png')), in release mode *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to *   // date; if you have any other folders that you want to ignore for performance reasons (gradle *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ *   // for example, you might want to remove it from here. *   inputExcludes: ["android/**", "ios/**"], * *   // override which node gets called and with what additional arguments *   nodeExecutableAndArgs: ["node"], * *   // supply additional arguments to the packager *   extraPackagerArgs: [] * ] */project.ext.react = [    entryFile: "index.js",    enableHermes: false,  // clean and rebuild if changing]apply from: "../../node_modules/react-native/react.gradle"apply from: '../../node_modules/react-native-unimodules/gradle.groovy'/** * Set this to true to create two separate APKs instead of one: *   - An APK that only works on ARM devices *   - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */def enableSeparateBuildPerCPUArchitecture = false/** * Run Proguard to shrink the Java bytecode in release builds. */def enableProguardInReleaseBuilds = false/** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US.  Note that * this variant is about 6MiB larger per architecture than default. */def jscFlavor = 'org.webkit:android-jsc:+'/** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and mirrored here.  If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */def enableHermes = project.ext.react.get("enableHermes", false);def keystorePropertiesFile = rootProject.file("keystore.properties");def keystoreProperties = new Properties()keystoreProperties.load(new FileInputStream(keystorePropertiesFile))android {    compileSdkVersion rootProject.ext.compileSdkVersion    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    dexOptions {        javaMaxHeapSize "4g"    }    defaultConfig {        applicationId "com.chatapp"        minSdkVersion rootProject.ext.minSdkVersion        targetSdkVersion rootProject.ext.targetSdkVersion        versionCode 1        versionName "1.0"    }    splits {        abi {            reset()            enable enableSeparateBuildPerCPUArchitecture            universalApk false  // If true, also generate a universal APK            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"        }    }    signingConfigs {        debug {            storeFile file('debug.keystore')            storePassword 'android'            keyAlias 'androiddebugkey'            keyPassword 'android'        }        release {            storeFile file(keystoreProperties['storeFile'])            storePassword keystoreProperties['storePassword']            keyAlias keystoreProperties['keyAlias']            keyPassword keystoreProperties['keyPassword']        }    }    buildTypes {        debug {            signingConfig signingConfigs.debug        }        release {            // Caution! In production, you need to generate your own keystore file.            // see https://facebook.github.io/react-native/docs/signed-apk-android.            signingConfig signingConfigs.debug            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"        }    }    // applicationVariants are e.g. debug, release    applicationVariants.all { variant ->        variant.outputs.each { output ->            // For each separate APK per architecture, set a unique version code as described here:            // https://developer.android.com/studio/build/configure-apk-splits.html            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]            def abi = output.getFilter(OutputFile.ABI)            if (abi != null) {  // null for the universal-debug, universal-release variants                output.versionCodeOverride =                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode            }        }    }    packagingOptions {       pickFirst 'lib/x86/libc++_shared.so'       pickFirst 'lib/x86_64/libjsc.so'       pickFirst 'lib/arm64-v8a/libjsc.so'       pickFirst 'lib/arm64-v8a/libc++_shared.so'       pickFirst 'lib/x86_64/libc++_shared.so'       pickFirst 'lib/armeabi-v7a/libc++_shared.so'    }}dependencies {    implementation fileTree(dir: "libs", include: ["*.jar"])    implementation "com.facebook.react:react-native:+"  // From node_modules    implementation project(':react-native-google-signin')    implementation 'com.facebook.fresco:fresco:2.0.0'    implementation 'com.facebook.fresco:animated-gif:2.0.0'    implementation project(':react-native-notifications')    implementation 'com.google.firebase:firebase-core:16.0.0'    if (enableHermes) {        def hermesPath = "../../node_modules/hermes-engine/android/";        debugImplementation files(hermesPath +"hermes-debug.aar")        releaseImplementation files(hermesPath +"hermes-release.aar")    } else {        implementation jscFlavor    }    addUnimodulesDependencies()}// Run this once to be able to run the application with BUCK// puts all compile dependencies into folder libs for BUCK to usetask copyDownloadableDepsToLibs(type: Copy) {    from configurations.compile    into 'libs'}apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)apply plugin: 'com.google.gms.google-services'com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

Failed to find Build Tools revision 23.0.1

$
0
0

I am trying to build my first app with react-native.

I am following these 2 tutorial:

I am sure that I installed all the requirements from the second link but when I try running my app with react-native run-android, I get the following error:

Error

I executed this command while running genymotion.

This is all that I have installed in Android SDK:

enter image description here

enter image description here

I tried to install Android build tools 23.0.1 but I get this error:

enter image description here

What should I do?

Error at launching React-Native in WebStorm

$
0
0

For the first time with WebStorm I created a new React-Native project.
I had never use Android Studio (which is installed, v3.6.2).
After that, I launched the App but got this:

"C:\Program Files\nodejs\node.exe" D:\Cartella_per_attivita_con_WebSTORM\con_server\Centrale\node_modules\react-native/local-cli/cli.js run-androidinfo Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.Jetifier found 967 file(s) to forward-jetify. Using 8 workers...info JS server already running.info Launching emulator...info Successfully launched emulator.info Installing the app...> Task :app:compileDebugJavaWithJavac FAILEDDeprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.Use '--warning-mode all' to show the individual deprecation warnings.See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings11 actionable tasks: 2 executed, 9 up-to-dateFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':app:compileDebugJavaWithJavac'.> Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_241 contains a valid JDK installation.BUILD FAILED in 3sError: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081FAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':app:compileDebugJavaWithJavac'.> Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_241 contains a valid JDK installation.BUILD FAILED in 3s    at makeError (D:\Cartella_per_attivita_con_WebSTORM\con_server\Centrale\node_modules\execa\index.js:174:9)    at D:\Cartella_per_attivita_con_WebSTORM\con_server\Centrale\node_modules\execa\index.js:278:16    at processTicksAndRejections (internal/process/task_queues.js:97:5)    at async runOnAllDevices (D:\Cartella_per_attivita_con_WebSTORM\con_server\Centrale\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:5)    at async Command.handleAction (D:\Cartella_per_attivita_con_WebSTORM\con_server\Centrale\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:186:9)error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.

In the system JAVA_HOME variable there is: C:\Program Files\Java\jdk-13

ScrollView not scrolling properly?

$
0
0

There is a ScrollView in my functional component. I am using an android phone connected to my laptop so that I can see the changes in the phone.

Problem:

When I slide on the right side of the phone screen the page scrolls. But when I slide at the center or left side of the phone screen the page does not scroll properly. The page bounces to the top and bottom.

This is my minimalistic code:

return (<TouchableWithoutFeedback style={{ flex: 1 }} onPress={Keyboard.dismiss}><SafeAreaView><Header title="Organizations" navigation={props.navigation} /><ScrollView><Block mb={spacing.huge}><Card>                         ......<FlatList                              .....                         />                         ......</Card></Block></ScrollView></SafeAreaView></TouchableWithoutFeedback>   )

I am getting this error in console:

 WARN  VirtualizedLists should never be nested inside plain ScrollViews with the same orientation - use another VirtualizedList-backed container instead.

Does anyone know how to solve this problem?


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 activate the dark mode in react native app when android theme set to dark mode?

$
0
0

I am developing a react native app which supports dark theme.

I used react navigation and created custom theme using React context. Now I can toggle between dark mode and light mode using a button. But I want to use the android theme (eg: dark mode) when opening the app. Which means if dark mode is enabled in the android, my app want to have dark mode enabled when opening the app.

Why is firebaseApp already initialized in React Native on Android?

$
0
0

When I try to run this code on android, I get the error FirebaseApp name [DEFAULT] already exists! In this thread, it says that firebaseApp is initialized on app startup, but then why can you call initializeApp like in this thread? It seems like my code is functionally similar to the code in the second thread, so why am I getting an error? It works fine on iOS, so I'm completely lost. What have I missed?

Edit: Forgot to mention that all of the testConfig values are stored in an .env file that is accessed by the react-native-config library.

Edit 2: Changing firebase.initializeApp(testConfig); to firebase.initializeApp(testConfig, 'fire'); fixes android, but breaks ios, causing error No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()

Code:

import firebase from '@react-native-firebase/app';import '@react-native-firebase/auth';        // for authenticationimport '@react-native-firebase/storage';     // for storageimport '@react-native-firebase/firestore';   // for cloud firestoreimport '@react-native-firebase/functions';   // for cloud functionsimport '@react-native-firebase/messaging';   // for cloud messagingimport Config from 'react-native-config'const testConfig = {  apiKey: Config.REACT_APP_FIREBASE_TEST_API_KEY,  authDomain: Config.REACT_APP_FIREBASE_TEST_AUTH_DOMAIN,  databaseURL: Config.REACT_APP_FIREBASE_TEST_DATABASE_URL,  projectId: Config.REACT_APP_FIREBASE_TEST_PROJECT_ID,  storageBucket: Config.REACT_APP_FIREBASE_TEST_STORAGE_BUCKET,  messagingSenderId: Config.REACT_APP_FIREBASE_TEST_MESSAGING_SENDER_ID,  appId: Config.REACT_APP_FIREBASE_TEST_APP_ID,  measurementId: Config.REACT_APP_FIREBASE_TEST_MEASUREMENT_ID};const fire = firebase.initializeApp(testConfig);

Logcat:

2020-04-16 11:05:17.269 25458-25543/com.nativeminutetech E/unknown:ReactNative: Exception in native call    java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!        at com.google.android.gms.common.internal.Preconditions.checkState(Unknown Source:29)        at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@19.3.0:295)        at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@19.3.0:268)        at io.invertase.firebase.common.RCTConvertFirebase.readableMapToFirebaseApp(RCTConvertFirebase.java:97)        at io.invertase.firebase.app.ReactNativeFirebaseAppModule.initializeApp(ReactNativeFirebaseAppModule.java:55)        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:790)        at android.os.Handler.dispatchMessage(Handler.java:99)        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)        at android.os.Looper.loop(Looper.java:164)        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)        at java.lang.Thread.run(Thread.java:764)

react native save file to internal memory

$
0
0

I have to save a text file in the main internal memory.I'm using react-native-fs, none of the Constants, it's allowing me to do this.

How can I do?Can you recommend other libraries that allow you to do this?

React Native Navigation Error: The action navigate with payload {"name": 192.168.100.189:19000", "params":{}} was not handled by any navigator

$
0
0

I am using react-navigation with my React Native application.

I keep on getting an error that is supposedly a development-only warning and on't be shown in production.

How do I fix the error below??

console.error: "The action 'NAVIGATE' with payload {"name":"192.168.100.189:19000","params":{}} was not handled by any navigator.

Do you have a screen named '192.168.100.189:19000'?

If you'r trying to navigate to a screen in a nested navigator, seehttps://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nestd-navigator.

This is a development-only warning and won't be shown in production."

Viewing all 29485 articles
Browse latest View live


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