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

React-native onPress() event doesn't work in Android

$
0
0

I am experiencing a very weird behaviour in my android emulator when using react-navigation v5 in my react native application, which makes me think is a bug. I found out that there is an open issue on the official react-native-navigation page. See here.

In every secondary screen (see UserProfileScreen below), in many react native-elements like TouchableOpacity Button or TextInput the onPress event doesn't work. It only works in the main screen of the navigator. (See HomeScreen below)

Here is an example of how I create my stack navigator:

import {createStackNavigator} from '@react-navigation/stack';

// some imports here

const HomeStackNavigator = createStackNavigator();
export const HomeNavigator = () => {
   return (
       <HomeStackNavigator.Navigator>
         <HomeStackNavigator.Screen name="HomeScreen" component={HomeScreen}/>
         <HomeStackNavigator.Screen name="UserProfileScreen" component={UserProfileScreen}/>
         <HomeStackNavigator.Screen name="UserSettingsScreen" component={UserSettingsScreen}/>
       </HomeStackNavigator.Navigator>   
    )
};

As a PoC I have the same code in the main and secondary screen:

<TouchableOpacity     
   onPress={() => Alert.alert("You pressed me!")} >     
   <Text> touch me</Text> 
</TouchableOpacity>

and I see the alert only in the main screen (HomeScreen).

If I make UserProfileScreen as the fist screen in my stack navigator above then it works (the onPress event) fine on this screen but not in the HomeScreen. So it seems that the onPress event is triggered only in the main screen!. On IOS it works fine in all screens. Any idea ? Let me know if you need some more code snippets.


Websockets with Android SDK 28 not working (React Native)

$
0
0

I have a RN app with websockets. The following code works in iOS, but not in Android.

useEffect(() => {
    const ws = new WebSocket('ws://localhost:3001')
    return () => ws.close()
}, [])

When I do a console.log on ws (constant), I get this (Android):

{"CLOSED": 3, "CLOSING": 2, "CONNECTING": 0, "OPEN": 1, "_eventEmitter": {"_subscriber": {"_currentSubscription": null, "_subscriptionsForType": [Object]}}, "_socketId": 3, "_subscriptions": [{"context": undefined, "emitter": [NativeEventEmitter], "eventType": "websocketMessage", "key": 3, "listener": [Function anonymous], "subscriber": [EventSubscriptionVendor]}, {"context": undefined, "emitter": [NativeEventEmitter], "eventType": "websocketOpen", "key": 3, "listener": [Function anonymous], "subscriber": [EventSubscriptionVendor]}, {"context": undefined, "emitter": [NativeEventEmitter], "eventType": "websocketClosed", "key": 3, "listener": [Function anonymous], "subscriber": [EventSubscriptionVendor]}, {"context": undefined, "emitter": [NativeEventEmitter], "eventType": "websocketFailed", "key": 3, "listener": [Function anonymous], "subscriber": [EventSubscriptionVendor]}], "readyState": 0}

I log every connection server-side, and when I use the iOS emulator, I see 'connection established'. When I use the Android emulator, I don't see any logs.

const ws = require('ws')
const wss = new ws.Server({
    port: 3001
})
wss.on('connection', (ws, req) => {
    console.log('connection established')
})

I'm using Android 9.0 Pie SDK v28. Do I need to change something in my AndroidManifest or so?

Edit: I have the following lines in AndroidManifest.xml:

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

Edit 2: The problem occurs when running the websocket server locally. Testing to echo.websocket.org works, and I've set up a remote websocket server and this works too!

Does someone know how to set up websockets to test locally on android?

Unable to resolve module `../images/icon.png` from `src\pages\home\index.js`:

$
0
0

I'm going through a problem that apparently seems to be simple, but I'm not managing to solve it.

I'm starting an application using React Native, and I'm wanting to import an image that is in a folder, but it informs me that the image does not exist in the folder, the biggest problem is that this folder is two folders behind my index that I am calling, I already tried to return the folders with '../', '.' , but I am not able to solve it.

I need help, because I don't know what to do anymore.

I put below the image of the error that is happening to me

react-native error message

React-Native Element changing size while scrolling

$
0
0

I'm trying to make a react-native scrollview with 3 (or more) elements where the element in the middle of the screen is always 1.75 times the normal element size, and while scrolling the size changes dynamically. Can I find when the element is in the center of screen if the size of the scrollview will be changing? Is it possible to do without some complicated mathematical approach? I was trying putting conditions to all elements' styles but can't find a way to determine when the condition is met.

 handleScroll(event) {
    var x = event.nativeEvent.contentOffset.x;
    var page = x / this.state.totalWidth;
    this.setState({ position: page })
}

isElementFocused(start, stop) {
    return (this.state.position >= start && this.state.position < stop);
}

Element:

<View style={styles.swipeBox,
                {
                    backgroundColor: this.isElementFocused(1, 2) ? this.getColor(1) : colors.primary,
                    width: this.isElementFocused(1, 2) ? this.getWidth(1) : this.state.baseWidth,
                    height: this.isElementFocused(1, 2) ? this.getHeight(1) : this.state.baseHeight,

                }}>
                    <Text>test</Text>
                </View>

React Native - How to load local image using the uri in Image Component?

$
0
0

I know we can load the local image with:

<Image source={require('folder/image.png')}/>

But i need to load the image like this:

<Image source={{uri: 'folder/image.png'}}/>

It works for network images but it doesn't work for local images and even it does not give any error for local images and silently does not display the image. Can anyone tell how to load the local image using the uri property?

React Native Navigation React Native CLI Autolinking error

$
0
0

Issue Description

I installed the library via npx react-native link react-native-navigation (and modifying the minSdkVersion in andoid/build.gradle).

When I run npx react-native run-android, the app is built and works fine, though I get the following error in the terminal:

error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually: 
  - react-native-navigation (to unlink run: "react-native unlink react-native-navigation")

Since the lib has been linked manually, I add an entry in the react-native.config.js file to prevent react native to try to autolink the lib, as in:

module.exports = {
    dependencies: {
        'react-native-navigation': {
            platforms: {
                android: null, // disable Android platform, other platforms will still autolink if provided
            },
        }
    }
  };

Now, the CLI error is not longer shown and the app is successfully built, but I get an error in the emulator:

TypeError: null is not an object (evaluating "this.nativeCommandsModule.setRoot()").

Which comes about at my first Navigation.setRoot(...); call:

[index.js]

const start = () => {
    Navigation.events().registerAppLaunchedListener(() => {
        registerScreens();
        gotoInitialising();
        // gotoLogin();
    });
};

start();

My question is, what extra step should I take to get the lib to work and to not have a React Native CLI error, at the same time.

Environment

React Native Navigation version: 6.0.1 React Native version: 0.61.5 Platform(s) (iOS, Android, or both?): Android Device info (Simulator/Device? OS version? Debug/Release?): Android emulator API 28 - (emulator version 29.2.1-5889189) - Debug build

What should I do to make webview resizes images in the content to fit the mobile screen

$
0
0

webview doesn't resize images in the content to fit the mobile screen.

I use from "react-native-webview" and I'm trying to make the web content fit into the mobile screen but images don't fit at all causing horizontal scrolling.

I used scalesPageToFit={true} but it didn't help. I also tried style={{ flex: 1, width: Dimensions.get('window').width}} and style={{ flex: 1, width:'100%', alignSelf: 'stretch' }} but I didn't get any changes. I tried scrollEnabled={false} but nothing works.

  • "react-native": "0.57.8"
  • "react": "16.6.3"
  • "react-native-webview": "^2.14.3"
  • android
  • redmi note 4 - android version 7.0
  • windows 10

Android Studio Emulator don't run the app

$
0
0

i'm new at programming and studying react-native. 1 month ago I installed everything and started to code normally testing the app in the emulator. I don't know if I did something wrong but, when I created another project and tried to run it in the emulator, the emulator runned the first project, then I erased the device, closed everything and now it don't run any app at all. I do the process like:

Open VSCode;
Open Android Studio, then the emulator;
npx react-native run-android;

terminal says

BUILD SUCCESSFUL in 36s
117 actionable tasks: 2 executed, 115 up-to-date
info Connecting to the development server...
info Starting the app on "emulator-5554"...
Starting: Intent { cmp=com.project_two/.MainActivity }

the node window

Loading dependency graph, done.
BUNDLE  [android, dev] ./index.js 100.0% (449/449), done.

in the emulator, it does loading from 10.0.2.2:8081 then closes this window and goes back to home screen. And if I try to open the app manually, it stops responding.


Error : WebView has been removed from react native

$
0
0

I built new React Native project yesterday using react-native-cli. But when running the project with my android phone, I got this error in red screen.

Invariant Violation: WebView has been removed from React Native. It can now be installed and imported from 'react-native-webview' instead of 'react-native'. See 'https://github.com/react-native-community/react-native-webview'.

scri

How can i regenerate ios and android folder?

$
0
0

How can I regenerate ios and android folder in React Native project?

react-native-cli: 2.0.1 react-native: 0.61.2

❯ react-native eject error Unrecognized command "eject". info Run "react-native --help" to see a list of all available commands.

❯ react-native upgrade --legacy true error: unknown option `--legacy'

How to fix OKHttp module conflict in Android ReactNative project with third-party SDK?

$
0
0

I'm working on ReactNative project that it have several native dependencies. When we were developing software, we noticed a crash in application. So we released project and launch on real device (XIAOMI Redmi Note 4x) and started to debug the crash and the only message we received was: https://i.stack.imgur.com/8n3Zq.jpg

And our native dependencies was :

implementation project(':@metrixorg_react-native-metrix')
implementation project(':lottie-react-native')
implementation project(':react-native-firebase')
implementation project(':react-native-vector-icons')
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.facebook.react:react-native:+"  // From node_modules
implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
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"
implementation 'com.android.support:multidex:1.0.3'
implementation('com.crashlytics.sdk.android:crashlytics:2.9.9@aar') {
    transitive = true
}

As you saw the crash log, we found out that it was definitely from this package: :@metrixorg_react-native-metrix.

The first solution was to remove the package, so we did it and the crash was resolved completely.

When we was sure the package have a problem, we tried to exclude group: 'com.squareup.okhttp3' from the package and built it again, unfortunately when ':@metrixorg_react-native-metrix' be in native dependencies, we have crash on different place of the application.

Latest changes in build.gradle dependencies:

dependencies {
    implementation(project(':@metrixorg_react-native-metrix')){
        exclude group: 'com.squareup.okhttp3'
    }
    implementation(project(':lottie-react-native')){
        exclude group: 'com.squareup.okhttp3'
    }
    implementation(project(':react-native-firebase')){
        exclude group: 'com.squareup.okhttp3'
    }
    implementation project(':react-native-vector-icons')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
    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"
    implementation 'com.android.support:multidex:1.0.3'
    implementation('com.crashlytics.sdk.android:crashlytics:2.9.9@aar') {
        transitive = true
    }
    //  implementation 'com.google.firebase:firebase-inappmessaging-display:17.2.0'
    //  implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'



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

Log react-native info:

System:
    OS: macOS Mojave 10.14.6
    CPU: (4) x64 Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz
    Memory: 83.49 MB / 8.00 GB
    Shell: 5.3 - /bin/zsh
Binaries:
    Node: 10.14.1 - /usr/local/bin/node
    Yarn: 1.15.2 - /usr/local/bin/yarn
    npm: 6.4.1 - /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, 25, 27, 28, 29
    Build Tools: 23.0.1, 25.0.3, 27.0.3, 28.0.2, 28.0.3
    System Images: android-27 | Google Play Intel x86 Atom
IDEs:
    Android Studio: 3.5 AI-191.8026.42.35.6010548
    Xcode: 11.2.1/11B500 - /usr/bin/xcodebuild
npmPackages:
    react: 16.9.0 => 16.9.0
    react-native: 0.61.5 => 0.61.5
npmGlobalPackages:
    react-native-cli: 2.0.1

Android react native environment, call Animated.timing.start when screen is locked, no callback is received

$
0
0

This is my code:

        this.disappearA = Animated.timing(
            this.state.leftA,
            {
                toValue: -WIDTH - OFFSET,
                duration: DURATION,
                easing: Easing.linear,
            }
        );

        this.dispearA.start(() => {
            this.dataIsA = false;
            this.doing = false;
        });

On my android phone, When screen is locked, this.dispeara.start's end callback is not be fired!
When screen is not locked, this.dispeara.start's callback Is called correctly
Why is that? how to solve this problem

React native control for user mode switching

$
0
0

My application built in react-native needs to support different user modes. When I am on the screen I don't know the user-mode I am in. My customer are complaining about it. Is there any control in ios/android or react-native that I can display on every screen to tell the user-mode currently selected.

The other option I am doing is to show the user mode in the drawer, but that makes the user click the drawer, verify user mode and go back to what he was doing.

Please suggest.

Task :react-native-firebase:compileReleaseJavaWithJavac FAILED

$
0
0

I clone my own repo. project in on react native, I installed node modules and set Jdk8 as per requirements of my project. Then i run my project using react-native run-android. show me error

Task :react-native-firebase:compileReleaseJavaWithJavac FAILED

FAILURE: Build failed with an exception.

  • What went wrong: Execution failed for task ':react-native-firebase:compileReleaseJavaWithJavac'.

    Could not create service of type GeneralCompileCaches using GradleScopeCompileServices.createGeneralCompileCaches().

  • 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 1m 3s 13 actionable tasks: 2 executed, 11 up-to-date 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

Command failed: ./gradlew installDebug

Error: Command failed: ./gradlew installDebug at checkExecSyncError (child_process.js:601:13) at Object.execFileSync (child_process.js:621:13) at runOnAllDevices (/Volumes/Transcend/Emjoy/admin_panel_app_emjoy/node_modules/react-native/local-cli/runAndroid/runAndroid.js:299:19) at buildAndRun (/Volumes/Transcend/Emjoy/admin_panel_app_emjoy/node_modules/react-native/local-cli/runAndroid/runAndroid.js:135:12) at isPackagerRunning.then.result (/Volumes/Transcend/Emjoy/admin_panel_app_emjoy/node_modules/react-native/local-cli/runAndroid/runAndroid.js:65:12) at at process._tickCallback (internal/process/next_tick.js:188:7)

My version of react-native,react-native-cli, react-native-firebase all packages is the same as a project required.

Receiving TypeError: undefined is not a function (near'...posts.map...') React-Native / Rails 6.0 API

$
0
0

I am trying to run my Expo App on the iPhone/Android devices, but I receive

"undefined is not a function (near'...posts.map...')"

But the application runs on iOS emulator...It does show the error on the Android emulator. I'm fairly new to React Native and I'm trying to figure out why it's not returning the objects for my iPhone (physical) and Android Emulator.

The full error is below and the code that I wrote will follow it. How can I fix this TypeError issue and correctly display the results on my iPhone/Android Emulator?

Full Error:

TypeError: undefined is not a function
(near'...posts.map')

    This error is located at:
     in Home (created by
     Context.Consumer)
     in Route (at App.js:21)
     in Switch (at App.js.30)
     in RCTSafeAreaView (at SafeAreaView.js:55)
     in SafeAreaView (at App.js:19)
     in App (at App.js:35)
     in Router (created by Memory Router)
    ....

My React Native Code:

import React, {useState, useEffect} from 'react';
import Axios from 'axios'
import {ScrollView} from 'react-native';
import PhotoPost from '../components/PhotoPost';
import ErrorBoundary from 'react-native-error-boundary'

const Home = () => {
 const [posts, setPosts] = useState([]);

 useEffect( () => {
  Axios.get('http://127.0.0.1:3000/image_post/index')
  .then(res => {
    setPosts(res.data)
  }).catch(e => setPosts(e.message))
}, []);

 return (
  <ScrollView>
    <ErrorBoundary>
      {posts.map((posts, index) => {
        return(
          <PhotoPost key={index} post={post} />
        )
      })}
    </ErrorBoundary>
  </ScrollView>
 )
}

export default Home

React Native app closes after saving a contact

$
0
0

I'm using react-native-contacts inside my react native app to save a contact.

Before saving I request WRITE permission from android.
It works, I open the contact form through my app and save it using the contact form. The contact is saving properly. But, after I have saved the contact, it goes to the home screen, not to my app.

I want to return to my app after the contact is saved.

here is my code,

saveContact = user => {
  var newPerson = {
    emailAddresses: [
      {
        label: "work",
        email: user.email
      }
    ],
    phoneNumbers: [
      {
        label: "mobile",
        number: user.mobileNumber
      }
    ],
    displayName: user.firstName + "" + user.lastName
  };

  PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_CONTACTS, {
    title: "Contacts",
    message: "This app would like to write contacts.",
    buttonPositive: "Please accept bare mortal"
  }).then(() => {
    Contacts.openContactForm(newPerson, (err, contact) => {
      if (err) throw err;
      // contact has been saved
    });
  });
};

How to return to app after saving contacts - React Native - react-native-contacts

$
0
0

I'm using react-native-contacts inside my react native app to save a contact.

Before saving I request WRITE permission from android.
It works, I open the contact form through my app and save it using the contact form. The contact is saving properly. But, after I have saved the contact, it goes to the home screen, not to my app.

I want to return to my app after the contact is saved.

here is my code,

saveContact = user => {
  var newPerson = {
    emailAddresses: [
      {
        label: "work",
        email: user.email
      }
    ],
    phoneNumbers: [
      {
        label: "mobile",
        number: user.mobileNumber
      }
    ],
    displayName: user.firstName + "" + user.lastName
  };

  PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_CONTACTS, {
    title: "Contacts",
    message: "This app would like to write contacts.",
    buttonPositive: "Please accept bare mortal"
  }).then(() => {
    Contacts.openContactForm(newPerson, (err, contact) => {
      if (err) throw err;
      // contact has been saved
    });
  });
};

How to detect 3rd party keyboard in react native (iOS and Android)

$
0
0

In native iOS we can specify shouldAllowExtensionPointIdentifier to disable 3rd party keyboard.

-(BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier
{

    if (extensionPointIdentifier == UIApplicationKeyboardExtensionPointIdentifier)
    {
        return NO;
    }

    return YES;
}

In android is there a solution?

Is there a NPM package to block or detect 3rd party keyboard on both iOS and Android? Or we to write it in native and integrate it?

React Native local assets images not showing some time on release mode

$
0
0

my local assets images are working fine on Debug mode. but when i build apk in release mode with command react-native run-android --variant=release at first all local images showing correct but after sometime while using app some image not showing and some are fine. i fix this issue by add android:largeHeap="true" this line in AndroidManifest.xml but this reduce app performance. can anyone help me how can i handle this problem.

issue is no android i didn't test this on ios.

React Info:

react: 16.9.0 => 16.9.0 
react-native: 0.61.2 => 0.61.2 

How to call two function on onpress event in react native?

$
0
0

In below code, I want to call both methods on onpress event but I'm facing some issues, please give some idea how to call two methods on onpress event.

One method for start chatting and second for changing images on onpress event. Thank you

chatStart = () => {
    var { msg } = this.state;
    var { o_code } = this.state;
    var ucod = o_code;
    //console.log(o_code);
    var { session } = this.state;
    //console.log(session);
    var { ocod } = this.state;
    //console.log(ocod);
    var { Name } = this.state;
    var user_name = Name;

    var request = new XMLHttpRequest();
    request.onreadystatechange = e => {
      if (request.readyState !== 4) {
        return;
      }

      if (request.status === 200) {
        console.log("success", request.responseText);
      } else {
        console.warn("error");
      }
    };

    // var msg = "good things take some time";

    console.log(user_name);

    request.open(
      "POST",
      "http://www.aonde.biz/mobile/getChat.php?ocod=" +
      ocod +
      "&ucod=" +
      ucod +
      "&session=" +
      session,
      true
    );
    request.setRequestHeader(
      "Content-type",
      "application/x-www-form-urlencoded"
    );
    request.send("message=" + msg + "&name=" + user_name + "&ocod=" + ocod);
};

changeImage = () => {
    console.log("state changed!");
    this.setState({
      uri: require("./35-reject-red.png")
    });
  };

<View>
  <TouchableOpacity activeOpacity={0.5} onPress={this.changeImage}>
    <Image source={this.state.uri} />
  </TouchableOpacity>
</View>
Viewing all 29768 articles
Browse latest View live


Latest Images

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