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

How to integrate App Events for Android on React Native?

$
0
0

I have read the documentation on FBSDK, and for event integration Full code


import { AppEventsLogger } from "react-native-fbsdk";

// Log a $15 purchase.
AppEventsLogger.logPurchase(15, "USD", { param: "value" });

which part it is placed, where it is placed on onPress or how

// Log a $ 15 purchase.
AppEventsLogger.logPurchase (15, "USD", {param: "value"});

Maybe it can provide examples or url links for this solution


onPanResponderRelease not working on android devices

$
0
0

When i am using panResponders on iOS devices it works properly but same code when i run on android devices it is not working as expected. Code is as below

componentWillMount() {
    this._panResponder = PanResponder.create({
        onStartShouldSetPanResponder: (evt, gestureState) => true,
        onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
        onMoveShouldSetPanResponder: (evt, gestureState) => true,
        onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,

        onPanResponderGrant: (evt, gestureState) => {
            return true;
        },
        onPanResponderTerminationRequest: (evt, gestureState) => {
            console.log('getting on android');
            return false;
        },
        onPanResponderRelease: (evt, gestureState) => {
            console.log('getting here')
            return true;
        },
        onPanResponderTerminate : (evt, gestureState) => {
            console.log('gets');
        }
    });
}

Also my scrollView snippet is as below.

<ScrollView
      ref={ref => this.myScroll = ref }
      {...this._panResponder.panHandlers}>

React Native onPanResponderGrant is not called in Android but it works fine in iOS

$
0
0

I'm trying to implement drawer in react native using PanResponder and Animated.

I have the following code:

CustomDrawer.js

import React, { Component } from 'react';
import {
    View,
    Text,
    TouchableHighlight,
    Modal,
    TouchableWithoutFeedback,
    Animated,
    Dimensions,
    TouchableOpacity,
    PanResponder
}
from 'react-native';
import { setTimeout } from 'core-js/library/web/timers';

const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height; 
const DRAWER_WIDTH = 300;
const SWIPE_THERSHOLD = DRAWER_WIDTH * 0.2;

class CustomDrawer extends Component {

    visible = false;
    starting = false;

    state = {
        drawerVisible: false,
    }


    constructor(props){
        super(props);
        const { drawerVisible } = this.state;        
        const panResponder = PanResponder.create({
            onStartShouldSetPanResponder: (evt, gestureState) => true,
            onStartShouldSetPanResponderCapture: (evt, gestureState) => false,
            onMoveShouldSetPanResponder: (evt, gestureState) => true,
            onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
            onPanResponderMove: (event, gesture) => {
                if(this.visible){
                    if(gesture.dx<0){
                        this.position.setValue({ x: gesture.dx, y: 0});
                    }
                    else if(gesture.dx<DRAWER_WIDTH){
                        this.position.setValue({ x: -DRAWER_WIDTH + gesture.dx, y: 0});
                    }


                }
            },
            onPanResponderRelease: (event, gesture) => {                
                if(this.visible) {
                    if(gesture.dx> 10){
                        this.starting = false;                        
                    }
                    if(gesture.dx>0){
                        if(gesture.dx>=SWIPE_THERSHOLD){
                            this.forceDrawer('right');
                        }
                        else{
                            this.resetAnim();
                        }
                    }
                    else if(gesture.dx!=0) {
                        if(gesture.dx < - SWIPE_THERSHOLD){
                            this.setState({ drawerVisible: false});
                            this.forceDrawer('left');
                        }       
                        else {
                            this.renderAnim();
                        }
                    }

                }
                if(this.starting){
                    this.resetAnim();
                }
            },
            onPanResponderGrant: (event, gesture) => {
                console.log(gesture)

                setTimeout(()=> {
                    if(gesture.x0<10 && !gesture.x0==0){
                        console.log(gesture.x0);
                        this.setState({ drawerVisible: true})
                        this.visible=true;
                        this.starting = true;
                        this.position.setValue({ x: 10- DRAWER_WIDTH, y: 0})
                    }
                }, 500)
                return true;
            },

        });

        this.state = { drawerVisible: false, panResponder }
    }

    forceDrawer(direction) {
        const x = direction === 'right' ? 0 : -DRAWER_WIDTH;

        Animated.timing(this.position,{
            toValue: {x: x, y: 0},
            duration: 400
        }).start();
    }
    componentWillMount() {
        this.position = new Animated.ValueXY({x: -SCREEN_WIDTH, y: 0});
    }

    renderAnim(){
        Animated.timing(this.position, {
            toValue: { x: 0, y: 0},
            duration: 400
        }).start();
    }

    resetAnim() {
        this.starting = false;
        this.setState({ drawerVisible: false});
        this.visible = false;
        Animated.timing(this.position, {
            toValue: { x: -SCREEN_WIDTH, y: 0},
            duration: 250
        }).start();
    }

    renderBackground() {
        if(this.state.drawerVisible) {
            return(
                <TouchableOpacity style={styles.backgroundDrawer}
                    onPress={ () => {
                        this.resetAnim();
                        this.setState({drawerVisible: false});
                    }}>
                </TouchableOpacity>
            )
        }
    }

    render() {
        return(
            <View style={{flex: 1}}
            {...this.state.panResponder.panHandlers}>
                <View style={styles.viewStyle}>
                    <TouchableOpacity onPress={()=> {
                        this.renderAnim();
                        this.setState({ drawerVisible: true})
                        this.visible=true
                    }}>
                        <Text>Open Drawer</Text>
                    </TouchableOpacity>
                </View>

                {this.renderBackground()}

                <Animated.View style={[this.position.getLayout(),styles.drawerStyle]}  
                >
                    <Text>Contents</Text>
                </Animated.View>
            </View>
        )
    }
}


const styles = {
    viewStyle: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'hidden'
    },
    backgroundDrawer: {
        height: SCREEN_HEIGHT,
        width: SCREEN_WIDTH,
        backgroundColor: 'rgba(0,0,0,0.2)',
        position: 'absolute'
    },
    drawerStyle: {
        backgroundColor: 'white', 
        justifyContent: 'center',
        alignItems: 'center',        
        width: DRAWER_WIDTH,
        height: SCREEN_HEIGHT,
        position: 'absolute',
        elevation: 6,
        overflow: 'hidden'
    },

}
export default CustomDrawer;

As you can see here, i'm trying to move the drawer view, when the user presses on left corner for 500ms and the drawer view moves by 10pixels and user can drag it.

This works fine on iOS as you can see here

CustomDrawer

image

But the same is not working in Android. I tried debugging and onPanResponderGrant is not called in Android.

[react-native]onPanResponderRelease on FlatList or ListView doesn't trigger in android

$
0
0

I have a FlatList component, and I want realize PanResponder API on it, below is part of my code:

componentWillMount() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: ()=>true,
      onMoveShouldSetPanResponder: ()=>true,
      onPanResponderGrant: (e, gestureState)=>this.panResponderStart(e, gestureState),
      onPanResponderMove: (e, gestureState)=>this.panResponderMove(e, gestureState),
      onPanResponderRelease: (e, gestureState)=>this.panResponderEnd(e, gestureState),
      onPanResponderTerminate: (e, gestureState)=>this.panResponderEnd(e, gestureState),
    });
}
panResponderEnd(e, gestureState) {
    //this._previousTop += gestureState.dy;
    this.setState({scrollTop:0});
    console.log('release');
}
...
<FlatList
    {...this._panResponder.panHandlers}
    ...

onPanResponderRelease doesn't trigger on FlatList or ListView or VirtualizedList component, OS is android, is it a RN's bug? how to resolve this problem, any help is appreciated.

React native flatlist can't render 20 items at ones

$
0
0

I have 20 JSON data set that get using the fetch method and show that in flatlist.

My issue is when I load that data and scroll to the end of list, it scrolls til 13th data only. 7 data won't show. My flatlist does not scroll the end of the data set.

I was attache my screenshot and my source code. if anyone can help me with this issue. is a big help for me. Thanks

Is there any limit flatlist rendering??

enter image description here

class CategoryList extends Component{
  constructor(props) {
    super(props);
  this.state={

    info: [],
    isLoading: true

  };
}
  static navigationOptions = {
    header: {
      visible: false,
    }
  }

  handlePress = async () => {
    fetch('http://209.97.172.234/index.php/testCV/jobCatogoryList', {
        method: 'POST',headers: {
          'Content-Type': 'application/json',
        }

  })
      .then((response) => response.json())
      .then((responseJson) => {
       this.setState({ info: responseJson.data});
      })
      .catch((error) => {
        console.error(error);
      });
  }

  componentDidMount(){
    this.handlePress();
  }

    render() {

 const { info } = this.state;
      return (
<View>
        <Header>
          <TouchableHighlight onPress={() => this.props.navigation.toggleDrawer()} >
            <MyCustomLeftComponent />
          </TouchableHighlight>

          <MyCustomCenterComponent name='Category' />
          <MyCustomRightComponent />
        </Header>
<Card containerStyle={[styles.cardContainer]} >

<SearchBar
  lightTheme
  placeholder='Type Here...' />

<View>

 <FlatList
        data={info.cList}
        renderItem={({ item }) => (
          <ListItem

        title={item.cName}
        badge={{ value: item.cCount, textStyle: { color: 'orange' }}}
          />
        )}
      />

 </View>
    </Card>
    </View>
      );
    }
  }

How to set text in center in react native

$
0
0

Hi I want to set Text in center, I tried justifyContent and alignItems to center but it didn't work for me, text is displaying at the top.

LoginScreenStyles.js

export default StyleSheet.create({
  ...ApplicationStyles.screen,
  container: {
    paddingBottom: Metrics.baseMargin
  },
  centered: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center"
  }
});

ApplicationStyles.js

const ApplicationStyles = {
  screen: {
    mainContainer: {
      flex: 1,
      backgroundColor: Colors.transparent
    },
    backgroundImage: {
      position: "absolute",
      top: 0,
      left: 0,
      bottom: 0,
      right: 0
    },
    container: {
      flex: 1,
      paddingTop: Metrics.baseMargin,
      backgroundColor: Colors.transparent
    },
    section: {
      margin: Metrics.section,
      padding: Metrics.baseMargin
    },
    sectionText: {
      ...Fonts.style.normal,
      paddingVertical: Metrics.doubleBaseMargin,
      color: Colors.snow,
      marginVertical: Metrics.smallMargin,
      textAlign: "center"
    },
    subtitle: {
      color: Colors.snow,
      padding: Metrics.smallMargin,
      marginBottom: Metrics.smallMargin,
      marginHorizontal: Metrics.smallMargin
    },
    titleText: {
      ...Fonts.style.h2,
      fontSize: 14,
      color: Colors.text
    }
  },
  darkLabelContainer: {
    padding: Metrics.smallMargin,
    paddingBottom: Metrics.doubleBaseMargin,
    borderBottomColor: Colors.border,
    borderBottomWidth: 1,
    marginBottom: Metrics.baseMargin
  },
  darkLabel: {
    fontFamily: Fonts.type.bold,
    color: Colors.snow
  },
  groupContainer: {
    margin: Metrics.smallMargin,
    flexDirection: "row",
    justifyContent: "space-around",
    alignItems: "center"
  },
  sectionTitle: {
    ...Fonts.style.h4,
    color: Colors.coal,
    backgroundColor: Colors.ricePaper,
    padding: Metrics.smallMargin,
    marginTop: Metrics.smallMargin,
    marginHorizontal: Metrics.baseMargin,
    borderWidth: 1,
    borderColor: Colors.ember,
    alignItems: "center",
    textAlign: "center"
  }
};

export default ApplicationStyles;

LoginScreen.js

import React, { Component } from "react";
import { View, Text } from "react-native";

// Styles
import styles from "./Styles/LoginScreenStyles";

export default class LoginScreen extends Component {
  render() {
    return (
      <View style={styles.mainContainer}>
        <Text style={styles.centered}>
          This probably isn't what your app is going to look like. Unless your
          designer handed you this screen and, in that case, congrats! You're
          ready to ship. For everyone else, this is where you'll see a live
          preview of your fully functioning app using Ignite.
        </Text>
      </View>
    );
  }
}

enter image description here

Android and CouchDB with react native

$
0
0

I'm learning to use react native for an Android application. I had install in my folder project PouchDB and also I have CouchDB.

I'm trying to understand how the connection with the db works using simple login and registration forms.

For example, i had create a js page called DB.js like this:

import PouchDB from 'pouchdb-react-native';
PouchDB.plugin(require('pouchdb-find'));
PouchDB.plugin(require('pouchdb-adapter-asyncstorage').default);
PouchDB.plugin(require('pouchdb-authentication'));

class DB {
    constructor(dbName, username, password, protocol, host, port){
        this.remoteDB = null;
        this.localDB = new PouchDB(dbName);
        this.replication(
          'dbName' = ‘myDBName’, 
          'username' = ‘myUsername’, 
          'password' = ‘myPassword’, 
          'protocol' = 'https', 
          'host' = ‘myHost’, 
          'port' = myPortNumber

          );}

      localdb(){
        return this.localDB;
      }

      syncDB(){
        this.localdb().sync(this.remoteDB, {
          live: true,
          retry: true,
          attachments:true,
        }).on('change', function (change) {
        // 
        }).on('paused', function (paused) {
        //  console.log('paused:' + paused)
        }).on('active', function (active) {
        //  console.log('active:' + active)
        }).on('error', function (error) {
        //  console.log('error:' + error)
        });
      }



      replication(dbName, username, password, protocol, host, port){
        this.createDB(dbName, username, password, protocol, host, port);
        this.loginDB(username, password);
      }

In the constructor, I initialized the database and then synchronized it.

Now, for example, I should create a form to sign up.

Register.js

    import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  Button,
  TouchableHighlight,
  Image,
  Alert
} from 'react-native';
import { Actions } from 'react-native-router-flux';


export default class SignUpView extends Component {

  constructor(props) {
    super(props);
    state = {
      fullName: '',
      email   : '',
      password: '',
    }
  }

  // 
  SignInUser(User){
    this.user = {
      _id:id,
      fullName: fullName,
      email: email,
      password: password 
    }

    return new Promise((resolve, reject) => {
      user.localdb().post(this.user)
      .then((response) => {this.user._rev = response.rev; resolve(response)})
      .catch((error) => {reject(error)})
    })
  }


  //

   render() {
    return (
      <View style={styles.container}>
        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/male-user/ultraviolet/50/3498db'}}/>
          <TextInput style={styles.inputs}
              placeholder="Full name"
              keyboardType="email-address"
              underlineColorAndroid='transparent'
              onChangeText={(fullName) => this.setState({fullName})}/>
        </View>

        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/message/ultraviolet/50/3498db'}}/>
          <TextInput style={styles.inputs}
              placeholder="Email"
              keyboardType="email-address"
              underlineColorAndroid='transparent'
              onChangeText={(email) => this.setState({email})}/>
        </View>

        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/key-2/ultraviolet/50/3498db'}}/>
          <TextInput style={styles.inputs}
              placeholder="Password"
              secureTextEntry={true}
              underlineColorAndroid='transparent'
              onChangeText={(password) => this.setState({password})}/>
        </View>

        <TouchableHighlight style={[styles.buttonContainer, styles.signupButton]} 
        onPress={ () =>  SignInUser(this.state) }>
          <Text style={styles.signUpText}>Sign up</Text>
        </TouchableHighlight>

        <TouchableHighlight style={[styles.buttonContainer, styles.signupButton]} onPress={() => Actions.scarlet()}>
            <Text style={styles.signUpText}>GoTo Scarlet</Text>
        </TouchableHighlight>
      </View>


    );
  }
}

And at the end, the js file to post in the database the information

SignInUser.js

export default class SignInUser {


    SignInUser(User){
    this.user = {
      _id:id,
      fullName: fullName,
      email: email,
      password: password 
    }

    return new Promise((resolve, reject) => {
      user.localdb().post(this.user)
      .then((response) => {this.user._rev = response.rev; resolve(response)})
      .catch((error) => {reject(error)})
    })
  }

}

When I start the emulator, I get an error in the function:

onPress={() => this.onClickListener('SignInUser')}>

I don't know if the error is due to the function or the code that was badly structured. Since I'm trying to understand as much as possible could you give me a hand? thanks a lot

How to get JSON.parser value after save to AsyncStorage using Json.stringfy in react native?

$
0
0

I want to use the data from JSON.stringify that I save locally from async storage, so I can manage them locally (like user data for login)

I already save it to AsyncStorage

componentDidMount = async () => {
      fetch('My_url', {
         method: 'GET'
      })
      .then((response) => response.json())
      .then((responseJson) => {
         console.log(responseJson);
         this.setState({
            data: responseJson
         })
      })
      .catch((error) => {
         console.error(error);
      });

   }

   saveData = async () => {
     try {
                await AsyncStorage.setItem('user', JSON.stringify(this.state.data));
                Alert.alert('Saved', 'Successful');
            } catch (error) {
                Alert.alert('Error', 'There was an error.')
            }

this is the JSON

0   
username    "admin2"
password    "*****"
access  "1"
name    "dwi"
phone_number    "087613721"
email   "**@****.com"
score   null
status  "0"
1   
username    "admin3"
password    "***"
access  "1"
name    "Satria"
phone_number    "****"
email   "*****3@*****.com"
score   null
status  "0"

and I try to get the value using this, but can't show anything in node console.log, it said "unidentified" (i just using press button on this)

displayData = async ()=>{
    try{
      let user = await AsyncStorage.getItem('user');
      let parsed = JSON.parse(user);
      console.log(parsed.email);
    }
    catch(error){
      alert(error)
    }
  }

can some JSON parser output use like to be database function? like for login so we can log in and check the data user from json.parser that I store in the data using async storage? or output some data that we want to be used like in where statement in the SQL ?


How to change React-Native App name in stores?

$
0
0

We're doing a rebranding and therefore having to change the app name.

Of course, as this has to be done with changing the domain, it'll include changing the config, Keychain domain, bundleId, etc.

Is there a way, for a quick start, to only change app name on AppStore and google play without digging into configuration files and without changing domain itself (yet)?

Error when building for production react native firebase app

$
0
0

I have implemented react native firebase into my rn app and it broke my production build (dev builds works fine).

Can someone please point me in direction on how to solve this? I use fastlane for building the app. It seems like the building script is unable to find the support libraries although I have added them to build.gradle.

Here is the error:

 Task :react-native-firebase:compileReleaseJavaWithJavac FAILED
/somepath/node_modules/react-native-firebase/android/src/main/java/io/invertase/firebase/ReactNativeFirebaseAppRegistrar.java:20: error: package android.support.annotation does not exist
import android.support.annotation.Keep;
                                 ^
/somepath/node_modules/react-native-firebase/android/src/main/java/io/invertase/firebase/ReactNativeFirebaseAppRegistrar.java:29: error: cannot find symbol
@Keep
 ^
....
                                            ^

Here is my app/build.gradle

apply plugin: "com.android.application"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

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
    iconFontNames: [ 'MaterialCommunityIcons.ttf', 'FontAwesome.ttf' ] // Name of the font files you want to copy
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.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

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

/**
 * Get password from keychain access app, works only on macosx
*/
def getPassword(String keyChain) {
   def stdout = new ByteArrayOutputStream()
   def stderr = new ByteArrayOutputStream()
   exec {
       commandLine 'security', '-q', 'find-generic-password', '-s', keyChain, '-w'
       standardOutput = stdout
       errorOutput = stderr
       ignoreExitValue true
   }
   //noinspection GroovyAssignabilityCheck
      stdout.toString().trim()
}

def keystorePass = getPassword("someapp_keystore")

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "cz.somecompany.someapp"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 62
        versionName "1.0"
        missingDimensionStrategy 'react-native-camera', 'mlkit'
        multiDexEnabled true
        resValue "string", "build_config_package", "cz.somecompany.someapp"
    }
    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('someapp_UPLOAD_STORE_FILE')) {
                storeFile file(someapp_UPLOAD_STORE_FILE)
                storePassword keystorePass
                keyAlias someapp_UPLOAD_KEY_ALIAS
                keyPassword keystorePass
            }
            v1SigningEnabled true
            v2SigningEnabled true
        }
    }
    flavorDimensions "version"
    productFlavors {
        dev {
            applicationIdSuffix ".dev"
            resValue "string", "app_name", "someapp dev"
        }

        stage {
            applicationIdSuffix ".stage"
            resValue "string", "app_name", "someapp stage"
        }

        prod {
            resValue "string", "app_name", "someapp"
        }
    }
    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.release
            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
            }

        }
    }
}

dependencies {
    implementation(project(':react-native-firebase'))

    // Firebase dependencies
    implementation "com.google.android.gms:play-services-base:16.1.0"
    implementation "com.google.firebase:firebase-core:16.0.9"
    implementation "com.google.firebase:firebase-messaging:18.0.0"

    compile 'com.android.support:multidex:1.0.1'
    implementation project(':react-native-config')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

// 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'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'

React Native Android build failed after upgrading 0.51 to 0.64

$
0
0

I have updated my react-native project from 0.51.0 to the latest version. After updating everything clearly as mentioned in the documentation, I am getting below error when I try to run my app. I already clean gradlew and .gradle/caches several times

1- cd android && ./gradlew clean && cd .. && react-native run-android

Here is build.gradle file

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 20
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.2")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

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

I expect to run the android app clearly but It gives the below error. I tried invalidating caches/restart too. But that was not helped me.

What went wrong: Execution failed for task ':app:processDebugResources'. Android resource linking failed /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:11: AAPT: error: attribute layout_constraintBottom_toBottomOf (aka com.turkcell.ppm:layout_constraintBottom_toBottomOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:11: AAPT: error: attribute layout_constraintStart_toStartOf (aka com.turkcell.ppm:layout_constraintStart_toStartOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:11: AAPT: error: attribute layout_constraintTop_toTopOf (aka com.turkcell.ppm:layout_constraintTop_toTopOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:23: AAPT: error: attribute layout_constraintEnd_toEndOf (aka com.turkcell.ppm:layout_constraintEnd_toEndOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:23: AAPT: error: attribute layout_constraintStart_toEndOf (aka com.turkcell.ppm:layout_constraintStart_toEndOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:23: AAPT: error: attribute layout_constraintTop_toTopOf (aka com.turkcell.ppm:layout_constraintTop_toTopOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:45: AAPT: error: attribute layout_constraintBottom_toBottomOf (aka com.turkcell.ppm:layout_constraintBottom_toBottomOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:45: AAPT: error: attribute layout_constraintTop_toBottomOf (aka com.turkcell.ppm:layout_constraintTop_toBottomOf) not found. error: failed linking file resources.

Android App is not running in full screen, but running in a mini window

$
0
0

My React Native app currently running in a mini window on android platform, either simulator or actual device. However no issue on iOS.

Any configuration that I should take note?

enter image description here

React Native iOS and Android folders not present

$
0
0

I'm new to react native, and I've been having some trouble understanding the folder structure of the app which should supposedly be present in the project folder on creation. Basically, when creating the project with npm, I get some starting files (App.js etc.) and a node_modules folder. I've got it up and running with expo, which created the .expo folder as well.

However, when I go to react's official documentation or look into plugins/addons on git they talk several times about an android and an iOS folder in the project root. But they are nowhere to be seen. I then got some hints that I could install and run react-native-upgrade-git, which allegedly would generate these missing folders. But that didn't work either.

So what have I missed? Where are those folders located?

Edit: Here is a screen dump from a Youtube tutorial showing the project structure I'm looking for:

enter image description here

App keeps crashing when i try to pick document for second time - React Native Android

$
0
0

I'm new to React Native. In my project, I'm using this package for selecting Document from storage. When I choosing a document for the first time its working fine, but when I try again to choosing a document, the application is crashed. I'm facing this error.

java.lang.RuntimeException: 
  at android.app.ActivityThread.callActivityOnStop (ActivityThread.java:4862)
  at android.app.ActivityThread.handleSleeping (ActivityThread.java:4994)
  at android.app.ActivityThread.access$3400 (ActivityThread.java:273)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2138)
  at android.os.Handler.dispatchMessage (Handler.java:112)
  at android.os.Looper.loop (Looper.java:216)
  at android.app.ActivityThread.main (ActivityThread.java:7625)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:524)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:987)

Caused by: java.lang.IllegalArgumentException: 
  at android.view.View.removeFrameMetricsListener (View.java:6565)
  at android.view.Window.removeOnFrameMetricsAvailableListener (Window.java:890)
  at androidx.core.app.FrameMetricsAggregator$FrameMetricsApi24Impl.remove (FrameMetricsAggregator.java:436)
  at androidx.core.app.FrameMetricsAggregator.remove (FrameMetricsAggregator.java:246)
  at com.google.firebase.perf.internal.zza.onActivityStopped (Unknown Source:64)
  at android.app.Application.dispatchActivityStopped (Application.java:269)
  at android.app.Activity.onStop (Activity.java:2042)
  at androidx.fragment.app.FragmentActivity.onStop (FragmentActivity.java:636)
  at androidx.appcompat.app.AppCompatActivity.onStop (AppCompatActivity.java:184)
  at android.app.Instrumentation.callActivityOnStop (Instrumentation.java:1490)
  at android.app.Activity.performStop (Activity.java:7708)
  at android.app.ActivityThread.callActivityOnStop (ActivityThread.java:4854)

I searched on google, but I can't get this error is coming from Firebase or Document Package. Help me to fix this error. Thank you

[react-native]could not connect to development server on android

$
0
0

When I run "react-native run-android",it gives me error:"could not connect to development server...".

  • Package server is running and i can access it directly from browser in mobile device.
  • My android device connected to computer has debugging enabled i checked it using adb devices command.
  • My android version is 4.4.4 so i cannot use adb reverse command.
  • I have set the ip address and port in Dev setting.
  • Usb debug is on.
  • OS is windows7.

So how to fix the red error screen issue?Any suggestion is appreciated!

Error screen


How to resolve React Native Error: task: react-native-maps:compileDebugJavaWithJavac FAILED

$
0
0

my project was working but when i installed react-native-maps and run react-native run-android i got this error: (I refer https://github.com/react-native-community/react-native-maps/blob/master/docs/installation.md and follow all steps)

> Task :react-native-maps:compileDebugJavaWithJavac FAILED
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:12: error: package androidx.core.view does not exist
import androidx.core.view.GestureDetectorCompat;
                         ^
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:13: error: package androidx.core.view does not exist
import androidx.core.view.MotionEventCompat;
                         ^
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:73: error: package androidx.core.content does not exist
import static androidx.core.content.PermissionChecker.checkSelfPermission;
                                   ^
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:73: error: static import only from classes and interfaces
import static androidx.core.content.PermissionChecker.checkSelfPermission;
^
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:108: error: cannot find symbol
  private final GestureDetectorCompat gestureDetector;
                ^
  symbol:   class GestureDetectorCompat
  location: class AirMapView
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:165: error: cannot find symbol
        new GestureDetectorCompat(reactContext, new GestureDetector.SimpleOnGestureListener() {
            ^
  symbol:   class GestureDetectorCompat
  location: class AirMapView
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:421: error: cannot find symbol
    return checkSelfPermission(getContext(), PERMISSIONS[0]) == PackageManager.PERMISSION_GRANTED ||
           ^
  symbol:   method checkSelfPermission(Context,String)
  location: class AirMapView
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:422: error: cannot find symbol
        checkSelfPermission(getContext(), PERMISSIONS[1]) == PackageManager.PERMISSION_GRANTED;
        ^
  symbol:   method checkSelfPermission(Context,String)
  location: class AirMapView
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:949: error: cannot find symbol
    int action = MotionEventCompat.getActionMasked(ev);
                 ^
  symbol:   variable MotionEventCompat
  location: class AirMapView
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
9 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-maps:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 2s
33 actionable tasks: 1 executed, 32 up-to-date
error Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
error Command failed: gradlew.bat app:installDebug. Run CLI with --verbose flag for more details.

My Android->build.gradle:

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
        playServicesVersion = "16.1.0" 
        androidMapsUtilsVersion = "0.5"
    }
    repositories {
        google()
        jcenter()
        mavenCentral()

    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.0")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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 {
            url "https://maven.google.com"
        }
    }
}

My App->build.gradle:

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.gardeshgaran"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    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
            }
        }
    }
}

dependencies {
    implementation project(':react-native-linear-gradient')
    implementation project(':react-native-gesture-handler')
    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 project(':react-native-maps')

}

// 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'
}

my AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.gardeshgaran">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">

      <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="*****"
      />


      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

please help me solve this error!

Expo SDK update causes Playstore app to crash (invalid SDK error)

$
0
0

I'm using expo for building a react native mobile app and it is ejected.

I recently published the android app to the Playstore on SDK 34. When I updated the app to SDK 35 and published it to the same channel, the SDK 34 version of the app on my android device will try to update and crash. The crash log showed this error: “Expo encountered a fatal error 34.0.0 is not a valid sdk version”

This person who posted on the Expo forum had the same problem I had (link). My understanding is that it could be due to a mismatch in the release channel endpoint. However, changing the release channel did not solve the crashing problem for the person but clearing data on the app would resolve this issue. This is the same for me, where I had to clear the data on the app in order to do an update without crashing.

Is there a better solution than having the user clear the data before they can update?

Cordova to native in Play Store

$
0
0

I have my app on my Play Store account and the app is been constructed in Cordova. I have converted the app to native Android and I need to provide a release. When I update the app package, corrupt error is being displayed. I want to provide the app and error is been displayed.

I expect that the error message would be disappeared and I want to update the app.

enter image description here

Manifest merger failed android.support.v4.app.CoreComponentFactory

$
0
0

Error given:

Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
    is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).

Gradle dependencies

dependencies {
implementation project(':react-native-image-resizer')
implementation project(':react-native-gesture-handler')
implementation project(':react-native-device-info')
implementation project(':react-native-camera')
implementation project(':react-native-agora')
implementation fileTree(dir: "libs", include: ["*.jar"])

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'com.android.support:animated-vector-drawable:28.0.0'
implementation 'com.android.support:exifinterface:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'

implementation "com.facebook.react:react-native:+"  // From node_modules
implementation 'com.getkeepsafe.relinker:relinker:1.3.0'
implementation 'com.android.volley:volley:1.1.0'
implementation files('src/main/jniLibs/HCNetSDK.jar')
implementation files('src/main/jniLibs/PlayerSDK.jar')
implementation 'com.ncorti:slidetoact:0.5.1'
implementation 'com.squareup.picasso:picasso:2.71828'

implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-messaging:17.1.0'
implementation 'com.pusher:push-notifications-android:1.0.2'
}

Edit: This GitHub ticket helped me solve it, seemed to be an androidx and react-native problem. Got gms and firebase versions here

React Native android build failed. SDK location not found

$
0
0

I have error when i start running android

What went wrong:
A problem occurred evaluating project ':app'.  
> SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.
Viewing all 28480 articles
Browse latest View live


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