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

'Unable to resolve module warnOnce' after following simple steps to run react-native application

$
0
0

Steps used are

1) create-react-native-app testApp

successfully created testApp directory.

2) inside android folder adding local.properties= {path to sdk}

3) now it says to run 'cd testApp' and 'npm run android'

4) after executing above steps successfully app-debug.apk is successfully installed on my connected device.

5) after launching testApp on my mobile it says below error.

enter image description here

6)Then searching for some link I got solved-unable-to load-script

7) after following it steps taken like creating assets directory 'android/app/src/main/assets' and running cmd 'react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest'

error: Unable to resolve module warnOnce from node_modules/react-native/Libraries/react-native/react-native-implementation.js: warnOnce could not be found within the project.

I am stuck also I have followed some links on StackOverflow but still not able to proceed.

Can somebody help me what to do next also are there any simpler steps to run this application on any android device easily?.


How to play sound in React Native?

$
0
0

I want to play a sound in React Native.

I have try to read here in zmxv/react-native-sound, but as a beginner like me, that's documentation make me confused how to apply that in React Native code.

Before I have try this one to make react native play sound on event and make a code like this:

import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'
const Sound = require('react-native-sound')


export default class MovieList extends Component {

    handlePress() {
        // Play some sound here
        let hello = new Sound('motorcycle.mp3', Sound.MAIN_BUNDLE, (error) => {
            if (error) {
              console.log(error)
            }
          })

          hello.play((success) => {
            if (!success) {
              console.log('Sound did not play')
            }
          })
    }

    render() {
        const { movie } = this.props
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this)}>
                <View>
                      <Text>Start</Text>
                </View>
            </TouchableOpacity>
        )
    }
}

And this is where I put my audio:

MyProject/android/app/src/main/res/raw/motorcycle.mp3

Project structure

Project Structure

So, what's wrong in my code?

How do I check the horizontal or vertical image status in React-Native?

$
0
0

I want to use the 'contain' feature when the vertical image comes and the 'stretch' feature when the horizontal image comes in the react-native. How do I check the horizontal or vertical status? For example:

<Image resizeMode={status==horizantal?'contain':'stretch'} />

How to create a backup and restore module in react native based Android application?

$
0
0

So I'am trying to design a data backup and restore application that will allow to save and retrieve the data using a cloud storage. And I'm looking for a library or a method to choose the files and data for backup and store them in a cloud storage as a backup which can be restored. Actually, I'm trying to save the data in a decentralized platform (Hyperledger Fabric) but I figured it will similar to storing in a cloud storage. It's ok if the solution only works for Android.

FlatList rendering as blank even when the data(Array) is supplied to the component

$
0
0

I am trying to render out a list of object data using FlatList in my React Native component, however I am getting a blank screen without any errors on the console which is why it is rather difficult to get to the bottom of the issue here. The data is made available to the component using Redux-Saga approach and supplied to the FlatList which is showing up a blank screen without any errors. To double check if the FlatList is working fine I did a mockup array in component and passed to the FlatList which renders out the UI as expected. Following is the code I am using here;

=======================================================

    class Mobile extends Component {

      componentDidMount() {
        let { readPostsAction } = this.props;
        readPostsAction();
      }

      renderItem = ({ item }) => {
        return (
          <View>
            <TouchableOpacity onPress={() => this.props.navigation.navigate('HomeDetails', { item })}>
              <Card>
                <CardItem header>
                  <Text style={styles.titleHeading}>{item.title}</Text>
                </CardItem>
                <CardItem cardBody>
                  <Content style={styles.cardContainer}>
                    <CustomCachedImage
              component={FitImage}
              source={{ uri: contentURL(item.attachments[0].url) }}
              style={{ width: width, height: 200 }}
                    />
                    <HTML tagsStyles={bodyText} html={reduceStringLength(contentText(item.excerpt))} />
                  </Content>
                </CardItem>
              </Card>
            </TouchableOpacity>
          </View>
        )
      }

      keyExtractor = (item, index) => item.id;

      render() {
        const { dataSource } = this.props;
        console.log('this.props', this.props);
        return (
          <View>
            <FlatList
              data={dataSource}
              keyExtractor={this.keyExtractor}
              renderItem={this.renderItem}
            />
          </View>
        );
      }
    }

    function mapStateToProps({ launchAppReducer }) {
      return {
        isLoading: launchAppReducer.isLoading,
        dataSource: launchAppReducer.data
      }
    }

    export default connect(mapStateToProps, { readPostsAction: actions.readPostsAction })(Mobile);

=======================================================

Here is the screenshot of the console Screenshot showing that the data is available in the component.

how can i access current location from web-page in react native webview

$
0
0

I have an app which developed in react-js. I want to integrate this app into react-native-webview. everything I right but I have two problems.
1-how can I access current location of the user in react-native-webview.
2-how can I debug my react-js(webpage) app inside react-native-webview.

for first problem
if I run webpage in a mobile browser and click on that event I'm getting current location of the user and at the same time when my react-native app getting started, I'm invoking permission for current location so in react-native-debugger i'm getting current location of user.i followed the similar example but this is related to react-native.
exact problem is how can I access the current location of webview in react-native-webview

for second problem
when I'm clicking on the event to fetch current location it is not showing the current location so ** I want to see what is error/response of that event**. because it is in webview I can access react-native logs in react-native-debugger but cannot see the web view logs in the debugger.I followed this one also but I don't know where to put that android config code.

my react-native code

import React, {Component} from 'react';
import {PermissionsAndroid} from 'react-native';
import { WebView } from "react-native-webview";

export default class App extends Component {

constructor(props){
    super(props);

    // To see all the requests in the chrome Dev tools in the network tab.
    XMLHttpRequest = GLOBAL.originalXMLHttpRequest ?
    GLOBAL.originalXMLHttpRequest :
    GLOBAL.XMLHttpRequest;

    // fetch logger
    global._fetch = fetch;
    global.fetch = function (uri, options, ...args) {
    return global._fetch(uri, options, ...args).then((response) => {
    console.log('Fetch', { request: { uri, options, ...args }, response });
    return response;
});
};
}
async requestLocationPermission() {
    try {
    const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
        'title': 'Location Access Permission',
        'message': 'Stanplus would like to use your location ' +
                    'so you we track you.'
        }
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can use the location");
        if (typeof window !== 'undefined'&& typeof window.navigator !== 'undefined'&& navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            (position) => {
            console.log(position.coords.latitude,'success');
            },
            (error) => {
            console.log(error,'fail')
            },
            { enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 }
        );
        }


    } else {
        console.log("Location permission denied")
    }
    } catch (err) {
    console.warn(err)
    }


}

componentDidMount() {
        this.requestLocationPermission();
    }

render() {
    return (
    <WebView 
        source={{uri: 'https://3fa4f958.ngrok.io/steptwo'}}
        style={{marginTop: 20}}
        onMessage={(event)=> console.log(event.nativeEvent.data)}
        scalesPageToFit={true}
    javaScriptEnabled = {true}
    />
    );
}
}

my React.js code which accesses current location

if (navigator.geolocation) {
        alert('event clicked');//in react-native app its showing the alert
        navigator.geolocation.getCurrentPosition(
        //but inside here react-native can't execute because of location permission issue
        position => {   
                let latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                let geocoder = new window.google.maps.Geocoder();
                //do other stuff----------
            }
        )
}

** I want to fetch current location when user click on webpage event inside react-native app and how to debug webview code**

please help stuck since 2 days ):

TextInput validation while typing

$
0
0

I have a TextInput for a specific format of e-mail address, and have a regex to validate it. I would like to validate it while the user types, with the exact value on the TextInput box, but I'm not getting that.

What I have done is actually add that validation to the OnChangeText method of the TextInput object. The mechanics seems to work, but it is validating against the content 1 letter behind the current content.

Ex.: If I have typed "June" it will validate "Jun" only. If I delete the "e", then it will get "June" and subsequently.

Is that correct, or is there somewhere else I can call my validation to have the expected effects?

<TextInput
    placeholder='Type in your email'
    style={Styles.Input}
    onChangeText={(text) => {this.setLogin(text)}}
    value={ this.state.login }
    autoCompleteType={"email"}
    autoFocus={true}
/>
...
...
...
setLogin = (input) => {
    this.setState({login: input});
    console.log(this.state.login_regex.test(this.state.login));
    if (!this.state.login_regex.test(this.state.login)) {
        this.setState({login_msg: "Use an internal mail address"});
    } else {
        this.setState({login_msg: ""});
    };
};   

View borderRadius style not applied on Android when view is inside a FlatList

$
0
0

I have a component that I used for selecting dates in a calendar. If a date is selected, the number should have circle as a background. I have wrapped the <Text> in a <View> with a borderRadius styling and the component itself works.

But when I render my component in a <FlatList>, the borderRadius is simply not applied on Android.

Check out the screenshots for iOS and Android.

I've tried a lot of adjustments but with no luck, and now reach out. An Expo example of my component code is here, the component itself is DaySelectorItem.js, and the list is in DaySelectorItem.js

Code here https://snack.expo.io/@esbenvb/android-square-circles

Thank you in advance :)

android shows squares

iOS works as expected


setState not working properly in release mode React native iOS

$
0
0

I'm fetching some data from a server to load it to my app, my app doesn't load until the app loads all the data, it works perfectly in the debug mode, but when I have to test it on release mode, I have to reload it in order to make it work, and that is not the idea. Here's my code:

import React, { Component } from 'react';
import { Alert, NetInfo, View, Text, AsyncStorage, TouchableWithoutFeedback, Linking, Platform } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Router from './Router';
import OnBoarding from './components/OnBoarding';
import Loading from './components/Loading';
import OneSignal from 'react-native-onesignal';
import axios from 'axios';
var DeviceInfo = require('react-native-device-info');

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
          usage: '',
          categories_hum: [],
          videoshum: [],
          categories_nov: [],
          novedades: [],
          tiendas: [],
          promociones: [],
          listadoCodigos: [],
          token: "",
          listadoCodigosRecibido: true,
          terminos: '',
          notFirst: false
        };
        this.changeUsage = this.changeUsage.bind(this);
      }

    onIds(device) {
      AsyncStorage.setItem('playerId', device.userId);
    }

    onOpened(openResult) {
     if(openResult.notification.payload.additionalData != undefined) {
      var opc = openResult.notification.payload.additionalData.opc;
      if(opc == 2) {
        opc = "2";
        AsyncStorage.setItem('opcion', opc);
      } else if(opc == 1) {
        opc = "1";
        AsyncStorage.setItem('opcion', opc);
      }
     }
    }


    componentWillMount() {
      OneSignal.addEventListener('ids', this.onIds);
      OneSignal.addEventListener('opened', this.onOpened);
    }

    componentDidMount() {
      NetInfo.isConnected.fetch().then(isConnected => {
           if(!isConnected) {
             Alert.alert (
               'No hay conexion',
               'No hay conexion a internet, debe poseer una conexion WiFi o celular para usar FerretotalApp'
             );
           }
        });

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/categoria-hum?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ categories_hum: response})
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/videoshum?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ videoshum: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/tienda_acf?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ tiendas: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/categorianovedades?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ categories_nov: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/ferretotalnovedades?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ novedades: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/promociones_activas?hola=1')
        .then(response => response.json())
        .then(
            response => this.setState({ promociones: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/listado_codigos_usuario?deviceID="'+DeviceInfo.getUniqueID()+'"')
        .then(response => response.json())
        .then(
          response => this.setState({ listadoCodigos: response, listadoCodigosRecibido: true})
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/terminos_condiciones?hola=1')
        .then(response => response.json())
        .then(
          response => this.setState({ terminos: response})
        );

        AsyncStorage.getItem('usage').then((result) => {
               if(!result){
                 this.setState({usage: "firstTime"});
               }else{
                 this.setState({usage: result});
               }
               //al colocar esto hara q salga siempre el onboarding
               //AsyncStorage.removeItem("usage");
             });

             AsyncStorage.getItem('notFirst').then((result) => {
               if(!result){
                 this.setState({notFirst: false});
                } else {
                   this.setState({notFirst: false})
                  }
               });

              AsyncStorage.getItem('token').then((value) => {
               if(!value){
                 var DeviceID = DeviceInfo.getUniqueID();
                 fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/recibir_token?deviceID="'+DeviceID+'"')
                 .then((response) => response.json())
                 .then((response) => {
                   if(response[0]){
                     AsyncStorage.setItem('token',response[0].access_token);
                     this.setState({token: response[0].access_token});
                   }
                 })
               } else {
                 this.setState({token: value})}
             });
             AsyncStorage.setItem('newCode',"false");
    }

    componentWillUnmount() {
      OneSignal.removeEventListener('ids', this.onIds);
      OneSignal.removeEventListener('opened', this.onOpened);
    }

    changeUsage(e) {
      this.setState({usage: "notFirst"});
      this.setState({notFirst: true});
    }

    render(){
      /*alert(this.state.categories_hum.length + "" + this.state.videoshum.length + "" + this.state.promociones.length
      + "" + this.state.novedades.length + "" + this.state.categories_nov.length + "" + this.state.tiendas.length + "" + this.state.listadoCodigosRecibido + "" + this.state.terminos.length) */

          if(this.state.categories_hum.length && this.state.videoshum.length && this.state.promociones.length
          && this.state.novedades.length && this.state.categories_nov.length && this.state.tiendas.length && this.state.listadoCodigosRecibido && this.state.terminos.length) {
             if(this.state.usage.length && this.state.usage == "firstTime"){
               //al colocar esto solo saldra el onboarding la primera vez
               AsyncStorage.setItem('usage', "notFirst");
               AsyncStorage.setItem('notFirst', true)
               //al colocar esto, guardara la fecha de instalacion de la aplicacion (realmente la primera vez que se mete)

                AsyncStorage.getItem('installed').then((result) => {
                if(!result) {
                  var date = new Date();
                  date = date.toString();
                  AsyncStorage.setItem('installed', date);
                }
              });

               return (
                  <OnBoarding changeUsage={this.changeUsage} terminos={this.state.terminos}/>
               );
             } else if(this.state.usage == "notFirst"&& this.state.notFirst == false) {
               return(
                <OnBoarding changeUsage={this.changeUsage} terminos={this.state.terminos} notFirst={true}/>
               );
            } else if(this.state.usage == "notFirst"&& this.state.notFirst) {
                    return (
                    <View style={{flex:1}}>
                        <Router
                            categories_hum={this.state.categories_hum}
                            videoshum={this.state.videoshum}
                            categories_nov={this.state.categories_nov}
                            novedades={this.state.novedades}
                            tiendas={this.state.tiendas}
                            listadoCodigos={this.state.listadoCodigos}
                            promociones={this.state.promociones}
                            token={this.state.token}
                            terminos={this.state.terminos}
                        />
                    </View>
                );
              }
          } else{
            return (
                <Loading/>
            )
        }
    }
}

export default App;

As you can see, I'm fetching all the data I need in the "ComponentDidMount" method, then I store the JSON data in multiple states and pass it to the screens I need, the thing is that in release mode, the states don't have anything after it "loads" and it only happens the first time you open the app and only in release mode, I check the response from fetch and it is ok, it brings the data. I have tried lot of things but I can't still figured out what it is since it works well in debug mode. Please if you have any ideas, you can tell me.

How to programmatically control the Youtube embed video quality in React Native

$
0
0

Is there a way I can set the quality of a youtube video in an Android webview? I have already tried the below options but non have worked.

  • The method setPlaybackQuality found in Playback Quality in IFrame Player is now deprecated.
  • Appending the parameter vq to the embedded URL.

    Example: src="http://www.youtube.com/embed/VIDEOID?vq=large"

To my understanding Youtube implemented a policy to control quality based on your bandwidth and possibly screen size. In the now deprecated older web based API it was possibly to list quality encodings and stream the desired version directly. But this is no longer an option.

Any help would be appreciated.

How to programmatically control the Youtube embed video quality

React Native Deep Linking Application Not Opening

$
0
0

I followed all the steps from both the articles mentioned below

https://hackernoon.com/react-native-deep-linking-for-ios-and-android-d33abfba7ef3

https://medium.com/react-native-training/deep-linking-your-react-native-app-d87c39a1ad5e

After the app gets installed on my phone, I tried opening the app from the browser by giving the URL as peopleapp://people/1 format. Instead of opening the app, the browser opens Google search to search for the above.

I Used this application to open my Application by using my App Link(https://play.google.com/store/apps/details?id=com.manoj.dlt&hl=en_US) it's working.

But how to open the application from browser or from another application Using my App Link ?

Anyone has idea, how to solve this issue ?

Here is my Total AndroidManifest Code`

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
    android:name=".MainApplication"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true">
    <activity
        android:name=".MainActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:screenOrientation="portrait"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustResize"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter android:label="filter_react_native">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="whizzard" android:host="article" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value='AIzaSyCr2maoYAmOb3Sg81mYnrBY_m7803DpwWU' />
    <!--android:value="AIzaSyDzm343wg-AxWbCNltYofmOK4pNjJItVF0"/>-->
    <meta-data
        android:name="io.fabric.ApiKey"
        android:value="337e8872b3f3f2368c758d3284514896e455281a" />
    <meta-data android:name="com.onesignal.NotificationAccentColor.DEFAULT" android:value="#db2b30" />
    <service android:name=".service.LocationTrackingService"/>
</application>

`

My Link is whizzard://article

Is it possible to use Node.JS based module from Java?

$
0
0

I was working on a React Native Native Module for Android. And it is written in Java (as what I researched from official docs and the internet). The problem is, I need to use a Node.JS based module to implement the functions that I want. Is there any possibility to use Node.JS module in Java?

The Node.JS module currently using a few Node native libraries such as fs and path. The code is 100% written using Node.JS.

Or is there any other way to create a React Native module without the use of Java?

The ultimate goal is to use this Node.JS based module to React Native App (without create a bridge between Node and React Native).

Android App crashes on OneSignal push notification

$
0
0

I developed a React Native app that crashes every time a push notification from OneSignal is received while the app is active.

The error is java.lang.NoSuchMethodError: No static method zzc.

If I receive the notification when the app is on background, there is no problem.

Here is my build.gradle file:

buildscript {
    ext {
        googlePlayServicesLocationVersion = "17.0.0"
        buildToolsVersion = "28.0.3"
        minSdkVersion = 21
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
        appCompatVersion = "1.0.2"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
    }
}

allprojects {
    repositories {

        configurations.all {
            resolutionStrategy.eachDependency { DependencyResolveDetails details ->
            def requested = details.requested
           if (requested.group == 'com.google.android.gms') {
              details.useVersion '17.0.0'
           }
           if (requested.group == 'com.google.firebase') {
              details.useVersion '17.0.0'
             }
           }
         }
        google()
        mavenLocal()

        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }

        maven {
           url "$rootDir/../node_modules/react-native-background-geolocation/android/libs"
        }

            maven {
                url "$rootDir/../node_modules/react-native-background-fetch/android/libs"
            }
    }
}


task wrapper(type: Wrapper) {
    gradleVersion = '4.10'
    distributionUrl = distributionUrl.replace("bin", "all")
}

And my app/build.gradle file:

apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    entryFile: "index.js"
]

apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
apply from: "../../node_modules/react-native/react.gradle"

Project background_geolocation = project(':react-native-background-geolocation')
apply from: "${background_geolocation.projectDir}/app.gradle"


def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    defaultConfig {
        applicationId "XXX"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 200
        versionName "24.10"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
                storeFile file(MYAPP_UPLOAD_STORE_FILE)
                storePassword MYAPP_UPLOAD_STORE_PASSWORD
                keyAlias MYAPP_UPLOAD_KEY_ALIAS
                keyPassword MYAPP_UPLOAD_KEY_PASSWORD
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // 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:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            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
            }
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation project(':@react-native-community_netinfo')
    implementation project(':react-native-fast-image')
    implementation project(':react-native-device-info')
    implementation project(':react-native-orientation-locker')
    implementation project(':@react-native-community_slider')
    implementation project(':react-native-webview')
    implementation project(':react-native-splash-screen')
    implementation project(':@react-native-community_async-storage')
    implementation project(':react-native-sentry')
    implementation project(':react-native-background-fetch')
    implementation project(':react-native-maps')
    implementation project(':react-native-iap')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-background-geolocation')
    implementation project(':react-native-webrtc')
    implementation project(':react-native-svg')
    implementation project(':react-native-onesignal')
    implementation project(':react-native-incall-manager')
    implementation project(':react-native-fs')
    implementation project(':react-native-reanimated')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.facebook.fresco:animated-gif:1.10.0'
    implementation "com.facebook.fresco:animated-base-support:1.3.0"
    addUnimodulesDependencies()
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

// [Added by react-native-background-geolocation] Purge debug sounds from release build.
def purgeBackgroundGeolocationDebugResources(applicationVariants) {
    if ((rootProject.ext.has("removeBackgroundGeolocationDebugSoundsInRelease")) && (rootProject.ext.removeBackgroundGeolocationDebugSoundsInRelease == false)) return
    applicationVariants.all { variant ->
        if (variant.buildType.name == "release") {
            println("[react-native-background-geolocation] Purging debug resources in release build")
            variant.mergeResources.doLast {
                delete(fileTree(dir: variant.mergeResources.outputDir, includes: ["raw_tslocationmanager*"]))
            }
        }
    }
}

Do you know where the problem could come from?

Updating Native Android App already on PlayStore with ReactNative build

$
0
0

I have an existing android app implemented in native android (JAVA) on play store. I am developing a ReactNative app now. I do not want to discard the existing android app from play store instead I want to update that android app by a ReactNative APK for android. Is this possible to update?

I have an error in react native null is not an object ''evaluating _ReanimatedModule.default.configureProps'

$
0
0

I installed react native on linux machine.I want to implement createBottomTabNavigator in my practice code.I create 5 folders and index.js inside them. navigate.js :

import {createAppContainer} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';

import Profile from './common/pages/profile';
import Home from './common/pages/home';
import Search from './common/pages/search';
import Camera from './common/pages/camera';
import Notification from './common/pages/notification';

const Navigate=createBottomTabNavigator({
    Profile:{screen:Profile},
    Home:{screen:Home},
    Camera:{screen:Camera},
    Search:{screen:Search},
    Notification:{screen:Notification}
});
export default createAppContainer(Navigate);

and main index.js:

import {AppRegistry} from 'react-native';
import Navigate from './navigate';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => Navigate);

now when I run in genymotion i have error:

  • null is not an object ''evaluating _ReanimatedModule.default.configureProps'

my package.json:

{
  "name": "myinstagram",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.8.6",
    "react-native": "0.60.5",
    "react-native-gesture-handler": "^1.4.1",
    "react-native-reanimated": "^1.2.0",
    "react-navigation": "^4.0.2",
    "react-navigation-tabs": "^2.4.1"
  },
  "devDependencies": {
    "@babel/core": "^7.6.0",
    "@babel/runtime": "^7.6.0",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.3.0",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.8.6"
  },
  "jest": {
    "preset": "react-native"
  }
}

Is there a way to record audio and start listening on the click, store on our local machine and convert that from speech to text?

$
0
0

Is there a way to record audio and start listening on the click, stop automatically when the user stops speaking , store that recorded audio in our local machine and convert that speech to text and send the text string to the LUIS(Microsoft) API using React Native(0.60) ?

Error: Cannot access realm that has been closed?

$
0
0

I used the old version of realm. Today I updated the react-native and realm to the latest version and I get this error?

previous version of realm is "realm": "1.13.0", previous version of reactn-naitve is "react-native": "0.44.0",

My code was working fine, this is sample of code i used `

const getSetting = (name, defaultValue = '') => {
  if (!realm.objects('settings').isValid())
    return defaultValue;

  let data = realm.objects('settings').filtered('name = "'+ name +'"');
  return !data || data.length === 0 ? defaultValue : data[0].value;
};
export const getDeviceKey = () => {
      let deviceKey = getSetting("device_key");
      logger('settings.get.device_key:', typeof deviceKey, deviceKey);
      return deviceKey;
    };

`

access environment variable in React-Native AndroidManifest.xml

$
0
0

I'm new to React Native. The task at hand is to set my Google API key in AndroidManifest.xml without exposing it, when pushed to GitHub. I set up an environment variable called API_KEY, but however I want to access it in the .xml, I get an error when trying to spin up the dev server.

So far I tried:

android:value=${env.API_KEY}
android:value="${env.API_KEY}"
android:value="${API_KEY}"

Thank you!

error: package android.support.annotation does not exist

$
0
0

i am having an issue with the android.support.annotation package.. this is my main build.gradle:

// 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"
        androidMapsUtilsVersion = "0.5+"

    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.0")
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        // instead of 'implementation' here, you should insert 'implementation' in android/app/build.gradle'
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
           // Local Maven repo containing AARs with JSC library built for Android
          url "$rootDir/../node_modules/jsc-android/dist"
       }
    }
}



subprojects {
    afterEvaluate {project ->
        if (project.hasProperty("android")) {
            android {
                compileSdkVersion 28 
                buildToolsVersion "28.0.3"
            }
        }
    }
}


and this is my \android\build.gradle:

buildscript {
    repositories {
        maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal 
    }
    dependencies {
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.1, 0.99.99]'
    }
}


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",
 *
 *   // 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"
]

apply from: "../../node_modules/react-native/react.gradle"


/**
 * 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

android {
    compileSdkVersion rootProject.ext.compileSdkVersion


    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        multiDexEnabled true
        applicationId "com.course"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 35
        versionName "1.1.32"
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // 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:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            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 '**/libjsc.so'
       pickFirst '**/libc++_shared.so'
       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 project(':@react-native-community_cameraroll')
    implementation project(':react-native-reanimated')
    implementation project(':react-native-i18n')
    implementation project(':@react-native-community_async-storage')       
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-randombytes')
    implementation project(':react-native-sentry')
    implementation project(':react-native-appsee')
    implementation project(':react-native-image-resizer')
    implementation project(':react-native-onesignal')
    implementation project(':react-native-mixpanel')
    implementation project(':react-native-svg')
    implementation project(':react-native-image-picker')
    implementation project(':react-native-fs')
    implementation project(':react-native-wheel-pick')
    implementation project(':react-native-fast-image')
    implementation project(':react-native-vector-icons')
    // implementation project(':realm')
    implementation project(':react-native-camera')
    implementation project(':react-native-linear-gradient')
    implementation project(':react-native-maps')
    implementation(project(':react-native-onesignal')){
      exclude group: 'com.google.android.gms'
    }

    // implementation(project(':react-native-maps')){
    //   exclude group: 'com.google.android.gms'
    // }
    implementation 'com.google.android.gms:play-services-base:16.0.0'
    implementation 'com.google.android.gms:play-services-basement:16.0.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation 'com.google.android.gms:play-services-tasks:16.0.0'
    implementation 'com.google.android.gms:play-services-maps:16.0.0'

    implementation 'org.webkit:android-jsc-cppruntime:+'
    // For even older gradle
    // compile 'org.webkit:android-jsc-cppruntime:+'
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'com.google.firebase:firebase-messaging:17.0.0'
    implementation 'androidx.annotation:annotation:1.1.0'

}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}


configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-v4:27.1.0'
        force 'org.webkit:android-jsc:r241213'
    }
}

apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

I already added this piece of code to my gradle.properties:

...
android.useAndroidX=true
android.enableJetifier=true

this is the full error message that I get:

Gradle may disable incremental compilation as the following annotation processors are not incremental: jetified-compiler-4.7.1.jar (com.github.bumptech.glide:compiler:4.7.1). Consider setting the experimental feature flag android.enableSeparateAnnotationProcessing=true in the gradle.properties file to run annotation processing in a separate task and make compilation incremental. Note: [2] Wrote GeneratedAppGlideModule with: [com.bumptech.glide.integration.okhttp3.OkHttpLibraryGlideModule, com.dylanvann.fastimage.FastImageOkHttpProgressGlideModule] C:\Users\Ofir\Desktop\Vegan Nation\VeganNation\node_modules\react-native-fast-image\android\build\generated\source\apt\debug\com\dylanvann\fastimage\GlideOptions.java:6: error: package android.support.annotation does not exist import android.support.annotation.CheckResult; ^ C:\Users\Ofir\Desktop\Vegan Nation\VeganNation\node_modules\react-native-fast-image\android\build\generated\source\apt\debug\com\dylanvann\fastimage\GlideOptions.java:7: error: package android.support.annotation does not exist import android.support.annotation.NonNull; ^ C:\Users\Ofir\Desktop\Vegan Nation\VeganNation\node_modules\react-native-fast-image\android\build\generated\source\apt\debug\com\dylanvann\fastimage\GlideRequest.java:8: error: package android.support.annotation does not exist import android.support.annotation.CheckResult; ^ C:\Users\Ofir\Desktop\Vegan Nation\VeganNation\node_modules\react-native-fast-image\android\build\generated\source\apt\debug\com\dylanvann\fastimage\GlideRequest.java:9: error: package android.support.annotation does not exist import android.support.annotation.NonNull; ^ C:\Users\Ofir\Desktop\Vegan Nation\VeganNation\node_modules\react-native-fast-image\android\build\generated\source\apt\debug\com\dylanvann\fastimage\GlideRequests.java:7: error: package android.support.annotation does not exist import android.support.annotation.CheckResult; ^ C:\Users\Ofir\Desktop\Vegan Nation\VeganNation\node_modules\react-native-fast-image\android\build\generated\source\apt\debug\com\dylanvann\fastimage\GlideRequests.java:8: error: package android.support.annotation does not exist import android.support.annotation.NonNull;

Thank you!

React native map-view not loading map

$
0
0

I was testing the new changes in my app on my android device and everything was ok, but when I turned on the internet so the google map could load nothing have changed. Is it some problem with my API key? I was using this code before and the map would always load normally.

<MapView
  style={{ flex: 1 }}
  region={this.state.place.coordinates}
  ref={(c)=> this._map = c}
  showsUserLocation={true} >
    {this.getMarkers()}
</MapView>

enter image description here

Viewing all 28476 articles
Browse latest View live


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