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

Android-studio: Unable to locate adb

$
0
0

I read the answers "unable to locate adb" using Android Studio and Error:Unable to locate adb within SDK in Android Studio and it didn't solve my problem.

I use the 4.0 android-studio and Ubuntu 18.04

When I click on "launch this AVD in the emulator", I get an error message "Unable to locate adb".I did look in the Android/Sdk/platform-tools, I have an "adb" executable.

After the "unable to locate adb" error message, the AVD still launches. But, when I try to run my react native app on it, I get the 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

I'm pretty sure the react-native part is fine, but that route to the emulator is not the same as before.

It was working before. Yesterday, out of the blue, when I launched my android-studio, it "restarted" (showing me the install wizard, etc), and it seems it messed up its configuration.

EDIT: [bad way] I created a new ubuntu user, re-install android studio + react-native. I still get the error message, still the AVD launches, but now React-native can install the app on it. So, now I can work with my new user, but I did not fix the problem.

EDIT2: [good way] @jpatmore fixed the android-studio part (see his answer).The react-native was still not working. There was probably some parameter of android-studio 3.6 still in the [my project]/android/[gradle or something]I cloned my repo in another folder, do another "npm install", "react-native link", and it was working.


【React Native - Android】Crash on Android with quick clicking many times while locking to portrait

$
0
0

I'm using the third-party react-native-orientation to handle screen orientation in my React Native project. On Android, when locking to portrait with quick clicking many times. It causes crash always on Android but works perfectly on iOS. Note that it works normally with clicking button only once to lock to landscape.

It really takes more than 3 days to find the solution but unresolved.

The error as follows:

Error calling RCTEventEmitter.receiveTouchesfolly::toJson: JSON object value was a NaN or INF
  • React Native info
  React Native Environment Info:    System:      OS: macOS 10.14.5      CPU: (4) x64 Intel(R) Core(TM) i3-8100B CPU @ 3.60GHz      Memory: 30.76 MB / 8.00 GB      Shell: 5.3 - /bin/zsh    Binaries:      Node: 12.10.0 - /usr/local/bin/node      Yarn: 1.17.3 - ~/.yarn/bin/yarn      npm: 6.11.3 - /usr/local/bin/npm      Watchman: 4.9.0 - /usr/local/bin/watchman    SDKs:      iOS SDK:        Platforms: iOS 13.2, DriverKit 19.0, macOS 10.15, tvOS 13.2, watchOS 6.1      Android SDK:        API Levels: 23, 26, 27, 28        Build Tools: 23.0.1, 26.0.1, 27.0.3, 28.0.2, 28.0.3        System Images: android-23 | Intel x86 Atom_64, android-23 | Google APIs Intel x86 Atom, android-23 | Google APIs Intel x86 Atom_64, android-26 | Google APIs Intel x86 Atom, android-27 | Intel x86 Atom_64, android-27 | Google APIs Intel x86 Atom, android-27 | Google Play Intel x86 Atom, android-28 | Google Play Intel x86 Atom    IDEs:      Android Studio: 3.5 AI-191.8026.42.35.5977832      Xcode: 11.3.1/11C505 - /usr/bin/xcodebuild    npmPackages:      react: ^16.6.0-alpha.8af6728 => 16.13.1      react-native: 0.57.4 => 0.57.4    npmGlobalPackages:      react-native-cli: 2.0.1      react-native-demo-for-npm: 1.0.16      react-native-update-cli: 0.1.0
  • Android studio console logs (error details):
D/receiver: 2D/receiver: 2I/HiTouch_HiTouchSensor: HiTouch Setting Switch, OFFI/HiTouch_HiTouchSensor: Checking pkgName: com.wanke Checking result: true    isSecrutiyIMEPopup:falseI/HiTouch_HiTouchSensor: HiTouch Setting Switch, OFFI/HiTouch_HiTouchSensor: Checking pkgName: com.wanke Checking result: trueI/HiTouch_HiTouchSensor: isSecrutiyIMEPopup:falseW/HiTouch_PressGestureDetector: Touch pointer move a lot. The moving distance of X is:229.0, limit is:60The moving distance of Y is:405.0, limit is:60I/HiTouch_HiTouchSensor: HiTouch Setting Switch, OFFI/HiTouch_HiTouchSensor: Checking pkgName: com.wanke Checking result: true    isSecrutiyIMEPopup:falseW/HiTouch_PressGestureDetector: Touch pointer move a lot. The moving distance of X is:Infinity, limit is:60The moving distance of Y is:Infinity, limit is:60E/unknown:ReactNative: Exception in native call    java.lang.RuntimeException: Error calling RCTEventEmitter.receiveTouches        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)        at android.os.Handler.handleCallback(Handler.java:888)        at android.os.Handler.dispatchMessage(Handler.java:100)        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)        at android.os.Looper.loop(Looper.java:213)        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:192)        at java.lang.Thread.run(Thread.java:929)     Caused by: java.lang.RuntimeException: folly::toJson: JSON object value was a NaN or INF        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)         at android.os.Handler.handleCallback(Handler.java:888)         at android.os.Handler.dispatchMessage(Handler.java:100)         at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)         at android.os.Looper.loop(Looper.java:213)         at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:192)         at java.lang.Thread.run(Thread.java:929) E/unknown:ReactNative: Exception in native call    java.lang.RuntimeException: Error calling RCTEventEmitter.receiveTouches        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)        at android.os.Handler.handleCallback(Handler.java:888)        at android.os.Handler.dispatchMessage(Handler.java:100)        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)        at android.os.Looper.loop(Looper.java:213)        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:192)        at java.lang.Thread.run(Thread.java:929)     Caused by: java.lang.RuntimeException: folly::toJson: JSON object value was a NaN or INF        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)         at android.os.Handler.handleCallback(Handler.java:888)         at android.os.Handler.dispatchMessage(Handler.java:100)         at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)         at android.os.Looper.loop(Looper.java:213)         at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:192)         at java.lang.Thread.run(Thread.java:929) 

AndroidManifest.xml configs:

<activity            android:name=".MainActivity"            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"            android:label="@string/app_name"            android:screenOrientation="portrait"            android:windowSoftInputMode="stateAlwaysHidden|adjustPan"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity>

I searched the all issues but it didn't help. Any help for that? Thanks

What do these errors mean in React-Native in my react-native project and how do I fix them?

$
0
0
Error: spawn ./gradlew EACCES    at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)    at onErrorNT (internal/child_process.js:469:16)    at processTicksAndRejections (internal/process/task_queues.js:84:21)

0 info it worked if it ends with ok

1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'android' ]

2 info using npm@6.14.5

3 info using node@v12.17.0

4 verbose run-script [ 'preandroid', 'android', 'postandroid' ]

5 info lifecycle @~preandroid: @

6 info lifecycle @~android: @

7 verbose lifecycle @~android: unsafe-perm in lifecycle true

8 verbose lifecycle @~android: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/jonas/Desktop/ProjectTastebuds2/TasteBuds/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin

9 verbose lifecycle @~android: CWD: /Users/jonas/Desktop/ProjectTastebuds2/TasteBuds

10 silly lifecycle @~android: Args: [ '-c', 'react-native run-android' ]

11 silly lifecycle @~android: Returned: code: 1 signal: null

12 info lifecycle @~android: Failed to exec android script

13 verbose stack Error: @ android: react-native run-android

13 verbose stack Exit status 1

13 verbose stack at EventEmitter. (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)

13 verbose stack at EventEmitter.emit (events.js:315:20)

13 verbose stack at ChildProcess. (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)

13 verbose stack at ChildProcess.emit (events.js:315:20)

13 verbose stack at maybeClose (internal/child_process.js:1021:16)

13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)

14 verbose pkgid @

15 verbose cwd /Users/jonas/Desktop/ProjectTastebuds2/TasteBuds

16 verbose Darwin 19.6.0

17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "android"

18 verbose node v12.17.0

19 verbose npm v6.14.5

20 error code ELIFECYCLE

21 error errno 1

22 error @ android: react-native run-android

22 error Exit status 1

23 error Failed at the @ android script.

23 error This is probably not a problem with npm. There is likely additional logging output above.

24 verbose exit [ 1, true ]

Keyboard is not opening automatically though autoFocus={true}

$
0
0

I have a TextInput inside a Modal with autoFocus={true}. As soon as Modal is opened TextInput is focused automatically but keyboard is not opening automatically.And surprisingly this is happening randomly. sometimes keyboard opens and sometimes not. This is happening in both emulator and real device.

Any suggestions to overcome this behavior? Thank You.

React Native text field inside webview got overlap at last textfield

$
0
0

in my react native app i have one webview and inside that i have 4 textfield on that so when i focus last text input at that time keyboard is overlapping last text field not scroll automatically below is m code

render() {return (<View style={styles.mainView} ><WebView      ref={r => this.webview = r}     style={{width:globals.screenWidth, height:globals.screenHeight}}     bounces={false}     style={{ flex: 1 }}     startInLoadingState     scalesPageToFit     javaScriptEnabledAndroid={true}     javaScriptEnabled={true}     domStorageEnabled = {true}     onNavigationStateChange={this.handleNavigationStateChange}     onLoadStart={() => {     }}     onLoadEnd={() => {     }}    source={{uri: this.state.url}}     onError={(error) => this.onError()}    /></View>);}

So any idea how can i solve this your all suggestions are appreciable

React-Native :java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so

$
0
0

I have just updated my project to use react-native version 0.60.2 . But when I am trying to run an application on Android device it gets crashed after launch screen. I got the following error logs :

E/AndroidRuntime: FATAL EXCEPTION: create_react_context    Process: com.tjspeed, PID: 3909    java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so        at com.facebook.soloader.SoLoader.doLoadLibraryBySoName(SoLoader.java:738)        at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:591)        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:529)        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:484)        at com.facebook.hermes.reactexecutor.HermesExecutor.<clinit>(HermesExecutor.java:20)        at com.facebook.hermes.reactexecutor.HermesExecutorFactory.create(HermesExecutorFactory.java:27)        at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:949)        at java.lang.Thread.run(Thread.java:760)

Few suggestions available here : https://github.com/facebook/react-native/issues/25601 but unfortunately none of them worked for me. Please suggest the workaround.

release apk com.facebook.react.common.javascriptexception:null is not an object (evaluating t(r(d[1])).default.direction react native

$
0
0

Descriptionwhen i publish the app in play store . it is showing the error. but it is working perfectly in emulator.

React Native version:React Native Environment Info:System:OS: Windows 10CPU: (4) x64 Intel(R) Core(TM) i5-2430M CPU @ 2.40GHzMemory: 4.16 GB / 7.91 GBBinaries:npm: 6.14.5 - C:\Program Files\nodejs\npm.CMD

enter image description here

Expo - APK bundle must contain the expected embedded asset

$
0
0

I'm new on react, and i tried to run my app but i got this following error

E/AndroidRuntime: FATAL EXCEPTION: main    Process: com.bits.bee.bwc, PID: 12601    java.lang.AssertionError: APK bundle must contain the expected embedded asset asset_c2f3d742a18a28238b7cd34a5d4b7316.png        at expo.modules.updates.loader.EmbeddedLoader.copyAllAssets(EmbeddedLoader.java:174)        at expo.modules.updates.loader.EmbeddedLoader.processManifest(EmbeddedLoader.java:137)        at expo.modules.updates.loader.EmbeddedLoader.loadEmbeddedUpdate(EmbeddedLoader.java:57)        at expo.modules.updates.UpdatesController.start(UpdatesController.java:286)        at expo.modules.updates.UpdatesController.initialize(UpdatesController.java:96)        at com.bits.bee.bwc.MainApplication.onCreate(MainApplication.java:98)        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1011)        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4552)        at android.app.ActivityThread.access$1500(ActivityThread.java:147)        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)        at android.os.Handler.dispatchMessage(Handler.java:102)        at android.os.Looper.loop(Looper.java:135)        at android.app.ActivityThread.main(ActivityThread.java:5255)        at java.lang.reflect.Method.invoke(Native Method)        at java.lang.reflect.Method.invoke(Method.java:372)        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)

Can someone explain to me how it's work because i looked it up in my asset folder there's nothing named like that. And how do i fix this? Thanks


React Native: Switch from createBottomTabNavigator to createMaterialBottomNavigator

$
0
0

I am fully aware that using createBottomTabNavigator will give you a nice iOS bottom tabs with no background color while createMaterialBottomNavigator will give you a background color and different setup on android device.

My goal is to to use createBottomTabNavigator on iOs device and then switch to createMaterialBottomNavigator on android device with all the setup like putting activeTintColor color, using shifting: true mode whenever you switch screen on android.

So what I did is I use the Platform API:

const MealsFavTabNavigator =    Platform.OS === 'android'        ? createMaterialBottomNavigator(navTabConfig)        : createBottomTabNavigator();

And then, create a possible config:

const navTabConfig = {    options={{        tabBarIcon: ({ focused, color, size }) => (<Ionicons name="ios-star" size={25} color={focused ? "tomato" : "black"} />        )    }}};

Then tried to switch this on my navigator:

<MealsFavTabNavigator.Screen                name="Meals"                component={MealsNavigator}                navTabConfig            />Which did not work. Here's the full code:    import React from 'react';    import { NavigationContainer } from '@react-navigation/native';    import { createStackNavigator } from '@react-navigation/stack';    import { Ionicons } from '@expo/vector-icons';    import { Platform } from 'react-native';    import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';    import CategoriesScreen from '../screens/CategoriesScreen';    import CategoryMealsScreen from '../screens/CategoryMealsScreen';    import MealDetailScreen from '../screens/MealDetailScreen';    import FavoritesScreen from '../screens/FavoritesScreen';    import HeaderButton from '../components/HeaderButton';    import { HeaderButtons, Item } from 'react-navigation-header-buttons';    import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';    import { CATEGORIES } from '../data/dummy-data';    import Colors from '../constants/colors';    const MealsNav = createStackNavigator();    const MealsNavigator = () => {        return (<MealsNav.Navigator                mode="modal"                screenOptions={{                    headerStyle: {                        backgroundColor: Colors.primaryColor,                    },                    headerTintColor: '#fff',                    headerTitleStyle: {                        fontSize: 17                    }                }}><MealsNav.Screen                    name="Categories"                    component={CategoriesScreen}                    options={{                        title: 'Meals Categories'                    }}                /><MealsNav.Screen                    name="CategoryMeals"                    component={CategoryMealsScreen}                    options={({ route }) => {                        const catId = route.params.categoryId;                        const selectedCategory = CATEGORIES.find((cat) => cat.id === catId);                        return {                            title: selectedCategory.title,                        };                    }}                /><MealsNav.Screen                    name="MealDetail"                    component={MealDetailScreen}                    options={{                        title: 'Meal Detail',                        headerRight: () => (<HeaderButtons HeaderButtonComponent={HeaderButton}><Item                                    title='Favorite'                                    iconName='ios-star'                                    onPress={() => console.log('Mark as the favorite')}                                /></HeaderButtons>                        ),                    }}                /></MealsNav.Navigator>        );    };    const MealsFavTabNavigator =        Platform.OS === 'android'            ? createMaterialBottomNavigator(navTabConfig)            : createBottomTabNavigator();    const navTabConfig = {        options={{            tabBarIcon: ({ focused, color, size }) => (<Ionicons name="ios-star" size={25} color={focused ? "tomato" : "black"} />            )        }}    };    const MealsTabNav = () => {        return (<NavigationContainer><MealsFavTabNavigator.Navigator                    tabBarOptions={{                        activeTintColor: 'tomato',                        inactiveTintColor: 'black',                    }}><MealsFavTabNavigator.Screen                        name="Meals"                        component={MealsNavigator}                        navTabConfig                    /><MealsFavTabNavigator.Screen                        name="Favorites"                        component={FavoritesScreen}                        options={{                            tabBarIcon: ({ focused, color, size }) => (<Ionicons name="ios-star" size={25} color={focused ? "tomato" : "black"} />                            )                        }}                    /></MealsFavTabNavigator.Navigator></NavigationContainer>        );    };    export default MealsTabNav;

How can I attain my goal of switching from createBottomTabNavigator to createMaterialBottomNavigator and then applying the basic styles on createMaterialBottomNavigator such as activeTintcolor and shifting mode.

Please help! I am super stuck!

best way to make a slider navigation in react native

$
0
0

I try to recreate this application in react-native :

enter image description here

But I don't have any clue for making the red component.I search on internet and I found react-navigation V5, But it look complicated just for that.

I also think to create a horizontal ScrollView, and every time I click on new 'page', rerender all the current view. But this is a good way?

Thanks for answers.

React Native: Back press and go back in web view not in screen (EXPO)

$
0
0

I am trying to add going back on webview when the android back button was pressed how can I do for this screen I did something like this but when canGoBack is false then I want navigation.goBack() is work but is not working

import React, { useState, useRef, useEffect } from 'react';import { StatusBar, BackHandler } from 'react-native';import WebView from 'react-native-webview';export default function Player({ route, navigation }) {    const [canGoBack, setCanGoBack] = useState(false);    const [currentUrl, setCurrentUrl] = useState('');    const webviewRef = useRef(null);    useEffect(() => {        BackHandler.addEventListener('hardwareBackPress', backButtonHandler);        return () =>            BackHandler.removeEventListener('hardwareBackPress',                backButtonHandler            );    }, []);    const backButtonHandler = () => {        webviewRef.current ? webviewRef.current.goBack() : navigation.goBack();        return true;    };    const { uri } = route.params;    return (<><StatusBar hidden={true} /><WebView                source={{                    uri: `https://${uri}`,                }}                ref={webviewRef}                onNavigationStateChange={(navState) => {                    setCanGoBack(navState.canGoBack);                    setCurrentUrl(navState.url);                }}            /></>    );}

Failed to build react-native-navigation v1

$
0
0

i am trying to use react-native-navigation v1, but while buildling, getting errors.

android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    ext {        buildToolsVersion = "29.0.2"        minSdkVersion = 26        compileSdkVersion = 29        targetSdkVersion = 29        supportLibVersion = "28.0.0"    }    repositories {        google()        jcenter()    }    dependencies {        classpath('com.android.tools.build:gradle:4.0.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()        maven { url 'https://www.jitpack.io' }    }}subprojects {    afterEvaluate {project ->        if (project.hasProperty("android")) {            android {                compileSdkVersion 29                buildToolsVersion "29.0.2"            }        }    }}

MainApplication.java

package com.nativeapp;import android.app.Application;import android.content.Context;import com.facebook.react.PackageList;import com.facebook.react.ReactApplication;import com.facebook.react.ReactInstanceManager;import com.facebook.react.ReactNativeHost;import com.facebook.react.ReactPackage;import com.facebook.soloader.SoLoader;import java.lang.reflect.InvocationTargetException;import com.reactnativenavigation.NavigationApplication;import com.reactnativenavigation.react.NavigationReactNativeHost;import java.util.List;//public class MainApplication extends Application implements ReactApplication  {public class MainApplication extends NavigationApplication {  private final ReactNativeHost mReactNativeHost =      //new ReactNativeHost(this) {        new NavigationReactNativeHost(this) {        @Override        public boolean getUseDeveloperSupport() {          return BuildConfig.DEBUG;        }        @Override        protected List<ReactPackage> getPackages() {          @SuppressWarnings("UnnecessaryLocalVariable")          List<ReactPackage> packages = new PackageList(this).getPackages();          // Packages that cannot be autolinked yet can be added manually here, for example:          //packages.add(new MyReactNativePackage());                    return packages;        }        @Override        protected String getJSMainModuleName() {          return "index";        }      };  @Override  public ReactNativeHost getReactNativeHost() {    return mReactNativeHost;  }  @Override  public void onCreate() {    super.onCreate();   // SoLoader.init(this, /* native exopackage */ false);    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());  }  /**   * Loads Flipper in React Native templates. Call this in the onCreate method with something like   * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());   *   * @param context   * @param reactInstanceManager   */  private static void initializeFlipper(      Context context, ReactInstanceManager reactInstanceManager) {    if (BuildConfig.DEBUG) {      try {        /*         We use reflection here to pick up the class that initializes Flipper,        since Flipper library is not available in release mode        */        Class<?> aClass = Class.forName("com.nativeapp.ReactNativeFlipper");        aClass            .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)            .invoke(null, context, reactInstanceManager);      } catch (ClassNotFoundException e) {        e.printStackTrace();      } catch (NoSuchMethodException e) {        e.printStackTrace();      } catch (IllegalAccessException e) {        e.printStackTrace();      } catch (InvocationTargetException e) {        e.printStackTrace();      }    }  }}

MainActivity.java

package com.nativeapp;//import com.facebook.react.ReactActivity;import com.reactnativenavigation.controllers.SplashActivity;public class MainActivity extends SplashActivity {}

android/setting.gradle

rootProject.name = 'nativeApp'apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)include ':app'include ':react-native-vector-icons'project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')include ':react-native-navigation'project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/android/app/')

android/app/build.gradle

apply plugin: "com.android.application"import com.android.build.OutputFile/** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ *   // the name of the generated asset file containing your JS bundle *   bundleAssetName: "index.android.bundle", * *   // the entry file for bundle generation. If none specified and *   // "index.android.js" exists, it will be used. Otherwise "index.js" is *   // default. Can be overridden with ENTRY_FILE environment variable. *   entryFile: "index.android.js", * *   // https://reactnative.dev/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 = [    enableHermes: false,  // clean and rebuild if changing]apply from: "../../node_modules/react-native/react.gradle"/** * Set this to true to create two separate APKs instead of one: *   - An APK that only works on ARM devices *   - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */def enableSeparateBuildPerCPUArchitecture = false/** * Run Proguard to shrink the Java bytecode in release builds. */def enableProguardInReleaseBuilds = false/** * 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);android {    compileSdkVersion 29    buildToolsVersion "29.0.2"    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    defaultConfig {        applicationId "com.nativeapp"        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://reactnative.dev/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            }        }    }}configurations.all {    resolutionStrategy.eachDependency { DependencyResolveDetails details ->        def requested = details.requested        if (requested.group == 'com.android.support'&& requested.name != 'multidex') {            details.useVersion "${rootProject.ext.supportLibVersion}"        }    }}dependencies {    implementation fileTree(dir: "libs", include: ["*.jar"])    //noinspection GradleDynamicVersion    implementation 'com.android.support:design:27.1.0'    implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"    implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"    implementation 'com.android.support:support-annotations:+'    implementation "com.facebook.react:react-native:+"  // From node_modules    implementation project(':react-native-vector-icons')    implementation project(':react-native-navigation')    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {      exclude group:'com.facebook.fbjni'    }    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {        exclude group:'com.facebook.flipper'    }    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {        exclude group:'com.facebook.flipper'    }    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 usetask copyDownloadableDepsToLibs(type: Copy) {    from configurations.compile    into 'libs'}apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)project.ext.vectoricons = [    iconFontNames: [ 'FontAwesome.ttf' ] // Name of the font files you want to copy]apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

And Error i am getting in Android studio Build is

Executing tasks: [clean, :app:assembleDebug, :react-native-vector-icons:assembleDebug] in project /home/nitin/reactNative/nativeApp/androidFAILURE: Build failed with an exception.* Where:Script '/home/nitin/reactNative/nativeApp/node_modules/react-native-navigation/android/prepare-robolectric.gradle' line: 12* What went wrong:A problem occurred evaluating script.> Could not create task ':downloadRobolectricDependencies'.> Unnecessarily replacing a task that does not exist is not supported.  Use create() or register() directly instead.  You attempted to replace a task named 'downloadRobolectricDependencies', but there is no existing task with that name.* 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.orgBUILD FAILED in 3s

And package.json is

{"name": "nativeApp","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","test": "jest","lint": "eslint ."  },"dependencies": {"react": "16.13.1","react-native": "0.63.1","react-native-navigation": "^1.1.484","react-native-vector-icons": "^7.0.0","react-redux": "^7.2.0","redux": "^4.0.5"  },"devDependencies": {"@babel/core": "7.10.5","@babel/runtime": "7.10.5","@react-native-community/eslint-config": "1.1.0","babel-jest": "25.5.1","eslint": "6.8.0","jest": "25.5.4","metro-react-native-babel-preset": "0.59.0","react-test-renderer": "16.13.1"  },"jest": {"preset": "react-native"  }}

I am using Lubuntu Operating system.nodejs 12.8.2npm 6.14.5

how to build apk of a react native firebase app? [closed]

$
0
0

I have build an app with react native and firebase with google sign-in authentication. and is working totally fine in both android as well as ios simulator. but after generating apk file of the same app(using expo build:android) the google sign-in function does not respond. is there any way to debug an apk file ?

Is there another way of making apk of react-native and firebase applications?

How to handle exit app in one screen not in the whole app - React Native?

$
0
0

I have some issue with BackHandler, the issue is

when running the app and go to the let's say Sign Up screen and touch the back in my mobile they will run the function and show the Alert to confirm, but now when I go to any other screen and touch the back they will I need to just back to the previous screen on every back BackHandler.exitApp(); runs, Although I write if the routname is SignUp just exit the app not other screens

this is my code

Sign Up

    import React from "react";    import {      Text,      TextInput,      ActivityIndicator,      View,      KeyboardAvoidingView,      ScrollView,      Image,      TouchableOpacity,      BackHandler,      Alert    } from "react-native";    export default class signUp extends React.Component {      constructor(props) {        super(props);      }      componentDidMount() {        BackHandler.addEventListener("hardwareBackPress", this.backPressed);      }      componentWillUnmount() {        BackHandler.removeEventListener("hardwareBackPress", this.backPressed);      }      backPressed = () => {    let { routeName } = this.props.navigation.state;    console.log("route is :  "+ routeName);    if (routeName == "SignUp") {      console.log("ROUTE :  "+ routeName);      Alert.alert("Exit App","Do you want to exit?",        [          {            text: "No",            onPress: () => console.log("Cancel Pressed"),            style: "cancel"          },          { text: "Yes", onPress: () => BackHandler.exitApp() }        ],        { cancelable: false }      );      return true;    } else {      return false;    }  };      render() {....}    }

Routes

import { createStackNavigator, createAppContainer } from "react-navigation";import React from "react";import { View } from "react-native";import Splash from "../screens/Splash";import Home from "../screens/Home";import SignUp from "../screens/SignUp";import SignIn from "../screens/SignIn";import ForgetPassword from "../screens/ForgetPassword";const Routes = createStackNavigator(  {    Splash: {      screen: Splash,      navigationOptions: {        header: null      }    },    SignUp: {      screen: SignUp,      navigationOptions: () => ({        // header: null        title: "Sign Up",        headerLeft: null,        headerTintColor: "#fc0301",        headerStyle: {          borderBottomColor: "white"        },        headerTitleStyle: {          color: "#fc0301",          textAlign: "center",          flex: 1,          elevation: 0,          fontSize: 25,          justifyContent: "center"        }      })    },    SignIn: {      screen: SignIn,      navigationOptions: {        title: "Sign In",        headerRight: <View />,        headerTintColor: "#fc0301",        headerStyle: {          borderBottomColor: "white"        },        headerTitleStyle: {          color: "#fc0301",          textAlign: "center",          flex: 1,          elevation: 0,          fontSize: 25,          justifyContent: "center"        }      }    },    ForgetPassword: {      screen: ForgetPassword,      navigationOptions: {        header: null      }    },    Home: {      screen: Home,      navigationOptions: {        header: null      }    }  },  {    initialRouteName: "Splash"  });export default createAppContainer(Routes);

React Native Text Breaking Into Two Lines

$
0
0

image_urlI have a React Native application and the text is breaking into two lines. I want it to render in a single line. Any help. Attaching the code and screenshot of screen

This line

<View><Text style={styles.product_name}>   {item.product_name}</Text></View

const styles = StyleSheet.create({  container: {    flex: 1,    alignItems: "center",    backgroundColor: colors.theme_bg_two,  },  header: {    backgroundColor: colors.theme_bg_three,  },  product_name: {    alignSelf: "center",    fontSize: 15,    fontWeight: "bold",    color: colors.theme_fg_two,  },});

replace the old application with the new one without installation

$
0
0

my client already has an app in the play store.he asked me to create an update for his application and it is already ready.how to replace the old application with the new one let us know that I only have the package and the Keystore ?can I do this without the user doing anything ?as if sometimes I open an application and notice changes without installing a new update

How do I get back to the app from Google Maps?

$
0
0

My app is made on React Native (Android only). When I click the button, the Google Maps app opens. Is there any way to implement a return to my app from Google Maps other than opening the entire list of apps open right now.

There is an idea to implement the app icon in the StatusBar when opening another app for a quick go back.

Do you have any other ideas ?

How to fix [Unhandled promise rejection: Error: Location provider is unavailable. Make sure that location services are enabled.]

$
0
0

I have just upgraded my app from Expo SDK 37.0.0 to 38.0.0. The app works fine on iOS but on Android I get the following warning and the app doesn't geolocate me on the map.

Development environment :

  • Expo SDK 38.0.0
  • React Native 0.62
  • Maps provider : Google Maps on Android & Apple Maps on iOS
  • React: 16.11.0
  • Device : Honor 8X/Android 10

Expected result : The app should geolocate me (the user) based on my position.Actuel result : The app doesn't geolocate me (the user) based on my position.Warning :

[Unhandled promise rejection: Error: Location provider is unavailable.Make sure that location services are enabled.]

What have I tried so far ?

  1. Ran expo upgrade once more to ensure that all of your packages are set to the correct version.

  2. Deleted package-lock.json and node_modules and ran npm install.

  3. Set Location.getCurrentPositionAsync({accuracy:Location.Accuracy.High})

  4. Set Location.getCurrentPositionAsync({ enableHighAccuracy: true })

      let { status } = await Permissions.askAsync(Permissions.LOCATION);  if (status !== 'granted') {    /* If user hasn't granted permission to geolocate himself herself */    Alert.alert("User location not detected","You haven't granted permission to detect your location.",      [{ text: 'OK', onPress: () => console.log('OK Pressed') }]    );  }  let location = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High });  this.setState({    userLat: location.coords.latitude,    userLng: location.coords.longitude,    navGeoStatus: true,    lat: location.coords.latitude,    lng: location.coords.longitude  });}```

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

$
0
0

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

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

However, I'm getting the following error:

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

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

i tried all available solution but still cant find the proper solution. i got the error while building react native application

$
0
0

FAILURE: Build failed with an exception.

  • What went wrong:Could not determine the dependencies of task ':app:installDebug'.

java.io.IOException: The filename, directory name, or volume label syntax is incorrect

  • 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 9s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

Viewing all 29695 articles
Browse latest View live