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

How to scan one barcode per time? [react-native-camera]

$
0
0

Actually i'm new to React and i'm trying to make a simple barcode scanner which show the scanned barcode in an alert and after pressing "OK" in the alert the user should be able to scan another barcode.

The issue is that the barcode is continuously scanned and when the alert is up it's hiding and showing every second the alert.

I was trying to do something like this to show the alert only once and if OK is pressed to be able to show again the alert but only in case the OK is pressed but that had no effect..

  onBarCodeRead = (e) => {
    if(!this.alertPresent){
      this.alertPresent = true;
          Alert.alert(
            "Barcode type is " + e.type,
            "Barcode value is " + e.data,
            [
                 {text: 'OK', onPress: () => this.alertPresent = false;},
            ],
              {cancelable: false},
          );
      }
  }

Here is full code of Barcode.JS

import React, { Component } from 'react';
import { Button, Text, View,Alert } from 'react-native';
import { RNCamera } from 'react-native-camera';
import BarcodeMask from 'react-native-barcode-mask';
class ProductScanRNCamera extends Component {

  constructor(props) {
    super(props);
    this.camera = null;
    this.barcodeCodes = [];
    this.alertPresent = false;
    this.state = {
      camera: {
        flashMode: RNCamera.Constants.FlashMode.auto,
      }
    };
  }

  onBarCodeRead = (e) => {
    if(!this.alertPresent){
      this.alertPresent = true;
          Alert.alert(
            "Barcode type is " + e.type,
            "Barcode value is " + e.data,
            [
                 {text: 'OK', onPress: () => this.alertPresent = false;},
            ],
              {cancelable: false},
          );
      }
  }


  pendingView() {
    return (
      <View
      style={{
        flex: 1,
        backgroundColor: 'lightgreen',
        justifyContent: 'center',
        alignItems: 'center',
      }}
      >
      <Text>Waiting</Text>
      </View>
    );
  }

  render() {


    return (
      <View style={styles.container}>
      <RNCamera
      ref={ref => {
        this.camera = ref;
      }}
      defaultTouchToFocus
      flashMode={this.state.camera.flashMode}
      mirrorImage={false}
      onBarCodeRead={this.onBarCodeRead.bind(this)}
      onFocusChanged={() => {}}
      onZoomChanged={() => {}}
      style={styles.preview}
      >
      <BarcodeMask/>
      </RNCamera>
      </View>
    );
  }
}

keystore not found for signing config 'release'.-- React native

$
0
0

I'm trying to generate a Signed APK for react native project. Followed steps from android and react native documentation.

my Build.gradle file

android {
compileSdkVersion 23
buildToolsVersion '26.0.2'

defaultConfig {
    applicationId "com.appmobile"
    minSdkVersion 16
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
    ndk {
        abiFilters "armeabi-v7a", "x86"
    }
}
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
        }
    }
}
buildTypes {
    release {
        signingConfig signingConfigs.release
        // minifyEnabled enableProguardInReleaseBuilds
        // proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
}
splits {
    abi {
        reset()
        enable enableSeparateBuildPerCPUArchitecture
        universalApk false  // If true, also generate a universal APK
        include "armeabi-v7a", "x86"
    }
}
// buildTypes {
//     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:
        // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
        def versionCodes = ["armeabi-v7a":1, "x86":2]
        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
        }
    }
}

}

I have placed keystore file in Android/app directory

my grade.properties

    android.useDeprecatedNdk=true
MYAPP_RELEASE_STORE_FILE=sampleReleasekeyStore.jks
MYAPP_RELEASE_KEY_ALIAS=*****
MYAPP_RELEASE_STORE_PASSWORD=*****
MYAPP_RELEASE_KEY_PASSWORD=*****

when executing cd android && ./gradlew assembleRelease.

Its throwing Build failed

Execution failed for task ':app:validateSigningRelease'. Keystore file /Users/username/Projects/appMobile/android/app/sampleReleasekeyStore.jks not found for signing config 'release'.

I'm using Mac environment. Please let me know where I'm going wrong.

Can not run react-native on android

$
0
0

How to fix this error on running react-native on android

Failed to construct transformer:  DuplicateError: Duplicated files or mocks. Please check the console for more info
at setModule (/home/user/HelloWorld/node_modules/jest-haste-map/build/index.js:620:17)
at workerReply (/home/user/HelloWorld/node_modules/jest-haste-map/build/index.js:691:9)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Promise.all (index 16960) {
   mockPath1: 'node_modules/react-native/template/package.json',
   mockPath2: 'package.json'
}

React-Native trying to run android, getting an error about /bin/sh: /usr/local/share/android-sdk/platform-tools/adb: No such file or directory

$
0
0

I have updated my $PATH to include the correct location of my adb sdk, but react-native is insisting on using /usr/local/share/android-sdk, instead of /Users/username/Library/Android/sdk/platform-tools. Is there another way to change this? It will not run my android emulator because of this error.

Here is my path:

/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/username/Library/Android/sdk:Users/username/Library/Android/sdk/platform-tools

bash profile

export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
export ANDROID_HOME=/Users/username/Library/Android/sdk
export ANDROID_SDK=/Users/username/Library/Android/sdk
export PATH=$PATH:/Users/username/Library/Android/sdk
export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools

React native run-android do not updating modified code

$
0
0

I am using React native 0.52.0 and react-native-cli 2.0.1 on my Windows PC for android development. Despite all the changes i have made. When I run react-native run-android, it builds successfully but when I run it, I get the default react native screen.

The result when I run react-native run-android- enter image description here

The app I get-

enter image description here

index.js

import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('albums', () => App);

app.js

import React from 'react'
import ReactNative, { Text } from 'react-native'

export default const App = () => {
  return (
    <Text>Hello World</Text>
  )
}

When i ran react-native init albums, it was just an index.js file that was created, there was no index.android.js or index.ios.js file What am I doing wrong?

Cannot resolve symbol 'com' in android studio

$
0
0

I'm doing google/facebook login in react native with firebase. When i trying to open it in android studio and got this error in 3rd step of integrate firebase in android ref

here is the error

How do I make a TextInput show the start of the entered text instead of the end in Android?

$
0
0

I have a TextInput in my react-native application. When I set the value prop and the value is longer than the length of the TextInput, it shows the text starting from the end and not the beginning. In iOS it works okay, it seems to be an Android issue. Is there a way to align the text to show from the start of the TextInput or whichever is the preferred?

This is what I see:

enter image description here

This is what I want:

enter image description here

Here's my code

<TextInput
defaultValue={address}
ref="searchInput"
autoCorrect={false}
style={searchStyles.searchInputField}
placeholderTextColor={'#ddd'}
placeholder="Location"
onChangeText={query => this.search(query)}
/>

React Native - How to Application X open Application Y if Application Y has been installed

$
0
0

I want My Application (say Application X) want to open Application Y, if Application Y installed. And work in Android and iOS (open App Store / Play store if Application Y not installed)

What i have done :

Linking.openURL(applicationStoreURL);

The code above success open Play Store/App Store of Application Y, but actually the application Y has been installed so i want to direct open to Application Y from Application X.


openDrawer react native Undefined is not an object

$
0
0

I'm having an issue where my application will give an error when trying to open the drawer using a function. I am able to swipe in from the left and can navigate with no problem but once the user navigates once the openDraw function will cause the app the rebuild in Expo and if I try the openDraw function again I get an error "Uncaught Error: undefined is not an object (evaluating 'o.openDraw) onPress@cached-bundle-%experience" Any help is greatly appreciated. URL for code in below https://snack.expo.io/@anthonygt/b8ff2c

The code is below if you just want to see it

App.js

import React, { Component } from 'react';
import DrawerNavigator from './src/components/DrawerNavigator';

export default class App extends Component {
  render() {
    return (
      <DrawerNavigator 
       />
    );
  }
}

DrawerNavigator

import React, { Component } from 'react';
import { Platform, Dimensions } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createDrawerNavigator, DrawerActions  } from 'react-navigation-drawer';
import StackNavigator from './StackNavigator'
import SettingsScreen from '../screens/SettingsScreen';
import HomeScreen from '../screens/HomeScreen';
import UserProfile from '../screens/UserProfile';

const MyDrawerNavigator = createDrawerNavigator ({
    Stack: { screen: StackNavigator},
    Dashboard: { screen: HomeScreen },
    Settings: { screen: SettingsScreen },
    Profile: { screen: UserProfile },
},

    {
        initialRouteName: 'Stack',
        drawerWidth: 300,
        drawerPosition: 'left',
    }
);

const AppContainer = createAppContainer(MyDrawerNavigator);

export default class DrawerNavigator extends Component {
    render() {
        return <AppContainer />;
    }
}

MyStackNavigator

import React, { Component } from 'react';
import { createStackNavigator, Header, } from 'react-navigation-stack'
import {createAppContainer} from 'react-navigation';
import { DrawerActions } from 'react-navigation-drawer';
import HomeScreen from'../screens/HomeScreen';
import UserProfile from '../screens/UserProfile';
import SettingsScreen from '../screens/SettingsScreen';

const MyStackNavigator = createStackNavigator(

{
    Home: HomeScreen,
    Profile: UserProfile,
    Settings: SettingsScreen,


},
{
    initialRouteName:'Home',
    defaultNavigationOptions:{
        title: 'app',
    }
}
);

const AppContainer = createAppContainer(MyStackNavigator);
export default class StackNavigator extends Component{
    render(){
        return <AppContainer screenProps={
            {openDraw: ()=> this.props.navigation.openDrawer()}       
    }/>;
    }
}

3 screens are all the same just name changed

import React, {useState, useEffect,Component} from 'react';
import {View, Text, FlatList, Image, StyleSheet, TouchableOpacity} from 'react-native';
import {Feather} from  '@expo/vector-icons';

    const HomeScreen = ({screenProps,navigation}) => {


    return (<View style={styles.container}>
        <Text>Home screen</Text>
        <TouchableOpacity  onPress={() => screenProps.openDraw()}> 
                <Feather style={styles.iconStyle} name ="menu"></Feather>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => navigation.navigate('Home')}>
                       <Text>Home</Text>
                    </TouchableOpacity>
            <TouchableOpacity onPress={() => navigation.navigate('Settings')}>
                       <Text>Settings</Text>
                    </TouchableOpacity> 

            <TouchableOpacity onPress={() => navigation.navigate('Profile')}>
                       <Text>Profile</Text>
                    </TouchableOpacity> 

 </View>
    );
};
const styles = StyleSheet.create({

    container: {
        marginTop:25,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    fontWeight: "bold",
    fontSize: 30,

    },


}); 
export default HomeScreen;

does react-native have autoCompleteDropdown?

Node not loading after selecting in node

$
0
0

I code in react-native with an emulator.

When I press ctrl + m -> reload my node just bundles again and reloads the app. But when I select something random (and do nothing with it) in node and press crtl + m again in my emulator, node does nothing anymore...

Is it a bug or just a simple thing i do wrong?

node v10.16.3 enter image description here

https://github.com/TheFuzzyLucario/node-express-course/issues/3

React-native-shake not detecting shake

$
0
0

I'm trying to get my android app to detect a shake, so the user can return to a previous screen. I have installed react-native-shake and linked the package. My code is below but i'm not sure why it won't pick up a shake. I'm using an android emulator and shaking it through the menu.

I added the console.log just to check for output but it's not printing.

componentDidMount() {
    RNShake.addEventListener("ShakeEvent", () => {
      //this.props.navigation.navigate("Search")
      console.log("SHAKE DETECTED")
    })
  }

  componentWillUnmount() {
    RNShake.removeEventListener("ShakeEvent")
  }

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.

react-native android error Failed to install the app native_modules.gradle' line: 170

$
0
0

running react-native run-android in windows but get this error:

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details. Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081 :ReactNative:Unexpected empty result of running 'npx --quiet --no-install react-native config' command from 'null' directory. :ReactNative:Running 'npx --quiet --no-install react-native config' command from 'null' directory failed.

FAILURE: Build failed with an exception.

  • Where: Script '/node_modules/@react-native-community/cli-platform-android/native_modules.gradle' line: 170

  • What went wrong: A problem occurred evaluating script.

    Command config unrecognized. Make sure that you have run npm install and that you are inside a react-native project.

react-native-firebase Push Notification not Showing in foreground

$
0
0

I'm trying to push notification through react-native-firebase package but the push notification only run in background not in foreground.

this is my class

import React from 'react';
import {Alert, AsyncStorage} from 'react-native';
import {GoogleSignin, GoogleSigninButton, statusCodes} from '@react-native-community/google-signin';
import SplashScreen from './component/splashscreen';
import {AccessToken, GraphRequest, GraphRequestManager, LoginButton} from 'react-native-fbsdk';
import firebase from 'react-native-firebase';

class Login extends React.Component {
    state = {userInfo: '', isSignInProgress: false, loggedIn: true, loading: false};

    async componentDidMount() {
        const enabled = await firebase.messaging().hasPermission();

        if (enabled) {
            await this.getToken();
        } else {
            await this.requestPermission();
        }

        await this.createNotificationListeners();

        if (await AsyncStorage.getItem('name') && await AsyncStorage.getItem('photo')) {
            this.props.navigation.replace('Index');
        } else {
            this.setState({
                loggedIn: false,
                loading: false,
            });
        }
    }

    componentWillUnmount() {
        this.notificationListener();
        this.notificationOpenedListener();
    }

    showAlert = (title, body) => {
        Alert.alert(
            title, body,
            [
                {text: 'OK', onPress: () => console.log('OK Pressed')},
            ],
            {cancelable: false},
        );
    };

    async createNotificationListeners() {
        const channel = new firebase.notifications.Android.Channel('test-channel', 'test-channel', firebase.notifications.Android.Importance.Max)
            // .setDescription('channel_name')
            .setSound('default');
        await firebase.notifications().android.createChannel(channel);
        /*
        * Triggered when a particular notification has been received in foreground
        * */
        this.notificationListener = firebase.notifications().onNotification(async notification => {
            const {title, body} = notification;
            const localNotification = new firebase.notifications.Notification({
                sound: 'default',
                show_in_foreground: true,
            })
                .setNotificationId(new Date().valueOf().toString())
                .setTitle('a')
                .setSound('default')
                .setBody('a')
                .setData({
                    now: new Date().toISOString(),
                    payload: data,
                })
                .android.setAutoCancel(true)
                .android.setBigText(body)
                // .android.setLargeIcon('ic_launchers')
                .android.setVibrate(1000)
                .android.setColor('#74c900')
                .android.setColorized(true)
                .android.setChannelId('test-channel') // e.g. the id you chose above
                // .android.setSmallIcon('ic_launchers') // create this icon in Android Studio
                .android.setPriority(firebase.notifications.Android.Priority.High);

            firebase
                .notifications()
                .displayNotification(localNotification);
            this.showAlert(title, body);
        });


        /*
        * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
        * */
        this.notificationOpenedListener = firebase.notifications().onNotificationOpened(notificationOpen => {
            const {title, body} = notificationOpen.notification;
            this.showAlert(title, body);
        });

        /*
        * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
        * */
        const notificationOpen = await firebase.notifications().getInitialNotification();
        if (notificationOpen) {
            const {title, body} = notificationOpen.notification;
            this.showAlert(title, body);
        }
        /*
        * Triggered for data only payload in foreground
        * */
        this.messageListener = firebase.messaging().onMessage((message) => {
            //process data message
            alert(JSON.stringify(message));
            console.log(JSON.stringify(message));
        });
    }

    async getToken() {
        const fcmToken = await firebase.messaging().getToken();
        await AsyncStorage.setItem('fcmToken', fcmToken);
        console.log(fcmToken);
    }

    async requestPermission() {
        try {
            await firebase.messaging().requestPermission();
            // User has authorised
            this.getToken();
        } catch (error) {
            // User has rejected permissions
            console.log('permission rejected');
        }
    }

    render() {
        if (this.state.loading) {
            return <SplashScreen/>;
        } else {
            return (
                <Text>App Page<Text/>
            );
        }
    }

}


export default Login;

and this is my android manifest xml

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

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

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <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.facebook.sdk.ApplicationId"
                   android:value="@string/facebook_app_id"/>
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:launchMode="singleTop"
        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" />
        <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

        <meta-data
                android:name="com.google.firebase.messaging.default_notification_icon"
                android:resource="@drawable/ic_launcher" />

        <meta-data
                android:name="com.google.firebase.messaging.default_notification_channel_id"
                android:value="@string/default_notification_channel_id"/>

        <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
        <receiver android:enabled="true"
                  android:exported="true"
                  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

this is the strings.xml

<resources>
    <string name="app_name">Tnt</string>
    <string name="facebook_app_id">2905xxxx</string>
    <string name="default_notification_channel_id" translatable="false">test-channel</string>
</resources>

any suggestions?? I already tried to apply the channel for FCM, is it really applied?

my react-native-firebase version is "^5.5.6" and my react-native version "0.61.2"

project: https://github.com/ericanthonywu/mobileTNT


Could not resolve all artifacts for configuration ':react-native-vector-icons: classpath'

$
0
0

I was runing a project(contacts from) "fullstack react native" book in react native. but I have a problem with react-native-vector-icons. when I run react-native run-android it showed me bellow error:

D:\android_Project\Vitel\React_Nativ\test\ZContacts>react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using
 "--no-jetifier" flag.
Jetifier found 874 file(s) to forward-jetify. Using 8 workers...
info JS server already running.
info Installing the app...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':react-native-vector-icons'.
> Could not resolve all artifacts for configuration ':react-native-vector-icons:
classpath'.
   > Could not find aapt2-proto.jar (com.android.tools.build:aapt2-proto:0.3.1).

     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/aapt2-p
roto/0.3.1/aapt2-proto-0.3.1.jar

* 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

BUILD FAILED in 48s

error Failed to install the app. Make sure you have the Android development envi
ronment set up: https://facebook.github.io/react-native/docs/getting-started.htm
l#android-development-environment. Run CLI with --verbose flag for more details.

Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8
081

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':react-native-vector-icons'.
> Could not resolve all artifacts for configuration ':react-native-vector-icons:
classpath'.
   > Could not find aapt2-proto.jar (com.android.tools.build:aapt2-proto:0.3.1).

     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/aapt2-p
roto/0.3.1/aapt2-proto-0.3.1.jar

* 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

BUILD FAILED in 48s

    at checkExecSyncError (child_process.js:629:11)
    at execFileSync (child_process.js:647:13)
    at runOnAllDevices (D:\android_Project\Vitel\React_Nativ\test\ZContacts\node
_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\
runOnAllDevices.js:94:39)
    at buildAndRun (D:\android_Project\Vitel\React_Nativ\test\ZContacts\node_mod
ules\@react-native-community\cli-platform-android\build\commands\runAndroid\inde
x.js:158:41)
    at then.result (D:\android_Project\Vitel\React_Nativ\test\ZContacts\node_mod
ules\@react-native-community\cli-platform-android\build\commands\runAndroid\inde
x.js:125:12)
    at process._tickCallback (internal/process/next_tick.js:68:7)

my Build.gradle is:

// 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
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:3.5.0')

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

and app/build.gradle is:

apply plugin: "com.android.application"

import com.android.build.OutputFile    
def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.zcantacts"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://facebook.github.io/react-native/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    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)

again i tried to run a new simple project so i do bellow commands: I tried a new simple project with this commads:

>react-native init testicons

>cd testicons

change build.gradle (change classpath("com.android.tools.build:gradle:3.4.2") to classpath("com.android.tools.build:gradle:3.5.0") ) then app run with react-native run-android (without import from react-native-vector-icons) and run these commands:

>npm install react-native-vector-icons

and

>react-native link react-native-vector-icons

i changed app.js:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React from 'react';
import {View,} from 'react-native';
import { MaterialIcons } from 'react-native-vector-icons';
const getTabBarIcon = icon => ({ tintColor }) => (
  <MaterialIcons name={icon} size={26} style={{ color: tintColor }} />
);

const App: () => React$Node = () => {return (<><View >{getTabBarIcon('list')}</View></>);};
export default App;

but when I run bellow cammand i had same error as before!

react-native run-android

that error was:

D:\android_Project\Vitel\React_Nativ\testicons>react-native run-android
error React Native CLI uses autolinking for native dependencies, but the followi
ng modules are linked manually:
  - react-native-vector-icons (to unlink run: "react-native unlink react-native-
vector-icons")
This is likely happening when upgrading React Native from below 0.60 to 0.60 or
above. Going forward, you can unlink this dependency via "react-native unlink <d
ependency>" and it will be included in your app automatically. If a library isn'
t compatible with autolinking, disregard this message and notify the library mai
ntainers.
Read more about autolinking: https://github.com/react-native-community/cli/blob/
master/docs/autolinking.md
info Running jetifier to migrate libraries to AndroidX. You can disable it using
 "--no-jetifier" flag.
Jetifier found 867 file(s) to forward-jetify. Using 8 workers...
info JS server already running.
info Installing the app...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':react-native-vector-icons'.
> Could not resolve all artifacts for configuration ':react-native-vector-icons:
classpath'.
   > Could not find aapt2-proto.jar (com.android.tools.build:aapt2-proto:0.3.1).

     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/aapt2-p
roto/0.3.1/aapt2-proto-0.3.1.jar

* 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

BUILD FAILED in 28s

error Failed to install the app. Make sure you have the Android development envi
ronment set up: https://facebook.github.io/react-native/docs/getting-started.htm
l#android-development-environment. Run CLI with --verbose flag for more details.

Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8
081

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':react-native-vector-icons'.
> Could not resolve all artifacts for configuration ':react-native-vector-icons:
classpath'.
   > Could not find aapt2-proto.jar (com.android.tools.build:aapt2-proto:0.3.1).

     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/aapt2-p
roto/0.3.1/aapt2-proto-0.3.1.jar

* 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

BUILD FAILED in 28s

    at checkExecSyncError (child_process.js:629:11)
    at execFileSync (child_process.js:647:13)
    at runOnAllDevices (D:\android_Project\Vitel\React_Nativ\testicons\node_modu
les\@react-native-community\cli-platform-android\build\commands\runAndroid\runOn
AllDevices.js:94:39)
    at buildAndRun (D:\android_Project\Vitel\React_Nativ\testicons\node_modules\
@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:
158:41)
    at then.result (D:\android_Project\Vitel\React_Nativ\testicons\node_modules\
@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:
125:12)
    at process._tickCallback (internal/process/next_tick.js:68:7)

can you help me? what is problem and how can I resolve it?

Could not resolve all artifacts for configuration ':pushwoosh-react-native-plugin:classpath'

$
0
0

I am trying to install Pushwoosh into my React Native app, and I am getting the following error:

> Could not resolve com.android.tools.build:gradle:2.3.3.
         > Could not get resource 'https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom'.
            > Could not GET 'https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom'.
               > maven.google.com: nodename nor servname provided, or not known
   > Could not resolve com.google.gms:google-services:4.2.0.
     Required by:
         project :pushwoosh-react-native-plugin
      > Could not resolve com.google.gms:google-services:4.2.0.
         > Could not get resource 'https://jcenter.bintray.com/com/google/gms/google-services/4.2.0/google-services-4.2.0.pom'.
            > Could not GET 'https://jcenter.bintray.com/com/google/gms/google-services/4.2.0/google-services-4.2.0.pom'.
               > jcenter.bintray.com

I am fairly new to React Native and Android development - so I'm not really sure what is going on here.

My main build.gradle file looks like this:

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

        // 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()

    }
}

and I followed the instructions on the github.

Can someone explain to me what exactly is the problem here?

Programmable voice(outgoing API)

$
0
0

I am using programmable voice(outgoing API) for my app. When I make a call to the client using this API, I get the same response status "NO ANSWER" when client did not respond to the call. And if client has no internet connection in other words data is off then also I get the same response status"NO ANSWER".

So how can I differentiate that "NO ANSWER" is received for which case (Internet is off or client did not picked the call.).

Passing navigation params in react-navigation to component's methods

$
0
0

Trying to figure out how params are passed in react-navigation. Once a user selected an option from the Filter using the left header button, loadItems(filter) should be called with that filter as a parameter. How do I catch such event?

export default class FavoritesView extends Component {
    static navigationOptions = ({navigation}) => ({
        headerLeft: (
            <Button
                onPress={()=>{FavoritesView.showFilteringMenu(navigation)}}
                title="Filter"
            />
        ),
    });
    static showFilteringMenu(navigation) {
        let FILTERS = [
            'A',
            'B',
            'C'
        ];
        ActionSheet.showActionSheetWithOptions({
                title: "Filter options",
                options: FILTERS
            },
            (buttonIndex) => {
                navigation.setParams({
                    selectedOption: FILTERS[buttonIndex]
                }); // A parameter is set here
            });
    }
    loadItems(filter) { // This function should be called
        StorageService.getItems(filter).then(v => this.setState({ data: v }));
    }
    render() {
        let {navigation} = this.props;
        return (
            <SafeAreaView style={styles.container}>
                <NavigationEvents
                    onWillFocus={payload => this.loadItems()} // This works only for initial load
                />
            </SafeAreaView>
        );
    }
}

How to create Horizontal Scrolling Flatlist with 2 rows and 3 columns visible in React Native?

$
0
0

I want to create a Horizontal Scrolling Flatlist with 2 rows and 3 columns visible. Data will be dynamic from api. I have managed to create vertical scrolling Flatlist which looks like this: Vertical Scrolling Flatlist. There is numOfColumns to specify count of columns but there is nothing for rows. When I tried to set horizontal={true}, layout became weird: Horizontal Scrolling Flatlist Also it throws error that numOfColumns can not be applied with Horizontal Scrolling Flatlist. Please refer attached screenshot for Desired output: Desired Output.

My Code for Vertical Scrolling Flatlist:

<FlatList
        ref={(ref) => { this.flatListRef = ref; }}
        style={{ width: '90%', marginTop: 10, marginLeft: 10, backgroundColor: 'transparent', borderRadius: 5, alignSelf: 'center' }}
        bounces={false}
        // horizontal={true}
        numColumns={3}
        data={this.state.categoryData}
        renderItem={({ item: data, index }) => {
        return (
          <ServiceView viewWidth={'100%'} viewHeight={'100%'} viewPaddingLeft={1} viewPaddingRight={10} viewPaddingTop={1} viewPaddingBottom={12} serviceName={(globalUserType == 'provider') ? data.services.name : data.name} serviceIconUrl={(globalUserType == 'provider') ? data.services.image : data.image} jobCount={(globalUserType == 'provider') ? '' : ''} showDot={(globalUserType == 'provider') ? false : false} 
           serviceAction={
           () => this.navigateTo('category', data)

         }/>

What changes should i make to get desired output.

Viewing all 28476 articles
Browse latest View live


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