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

Call function on scroll once in React-Native

$
0
0

I'm building an app, where I have a realizable header called <SearchBar /> which has prop isCollaped (value can be true or false) which opens and closes the container, and a <ScrollView /> (Screenshot below, sorry for not having text in English).Screenshots of an app:

Case when isCollaped == false

Case when isCollaped == true

I want to collapse the <SearchBar /> when starting to scroll the <ScrollView /> so I am setting the value of isCollaped to true, and it works, but because of <ScrollView /> calling onScroll every 200ms, and Scrolling animation not stopping after releasing a finger, when I try to open the <SearchBar /> again by pressing on it, and if the scroll animation is still active, I'm getting a really buggy animation that collapses the <SearchBar /> again.

This part of the code resizes the SearchBar when pressing on it:

collapseSearchBar = () => {   this.setState({      searchBarCollapsed: !this.state.searchBarCollapsed,   });};

This is the <SearchBar/>:

<SearchBar   isCollapsed={this.state.searchBarCollapsed}   onCollapse={this.collapseSearchBar}   onSearch={this.search}/>

This is the code for <ScrollView />:

<ListView      ref='mainScrollView'      dataSource={this.state.dataSource}      renderRow={(rowData) => {          return this._renderRow(rowData, this.props.navigation);      }}      onScroll={() => {        if (!this.state.searchBarCollapsed) {          this.setState({            searchBarCollapsed: true          });        }      }}/>

My question is: How can I make a <ScrollView /> call onScroll just once, when user swipes it, and not all the time (every 200ms, for about 3 seconds after the animation starts), while the animation is active.


Execution failed for task ':app:packageRelease'

$
0
0

I'm trying to create an aab file and test it.I can make it, with ./gradlew bundleReleaseWhen I want to test the aad file on my device, I run react-native run-android --variant=release, but I got this error :

> Task :app:packageRelease FAILED472 actionable tasks: 4 executed, 468 up-to-dateFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':app:packageRelease'.> A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable> java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError* 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 14serror 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 app:installRelease -PreactNativeDevServerPort=8081

I don't know what to do to resolve this. I can't run my aab file in my device.

react-native-cli: 2.0.1react-native: 0.63.0

React Native Picker Not Rendering Options

$
0
0

I'm trying to implement a select dropdown menu in a React Native application using npm's @react-native-picker/picker package.

I successful did it in one of the application's views/screens and tried to replicate by the same way but the dropdown menu is not rendering the options.

Checking the redux's store is possible to see the data that should be rendered, and in other view it does render. The data is the same for both screens such as the picker component.

return (<><DefaultHeader navigation={navigation} /><Container><ScrollView          refreshControl={<RefreshControl              refreshing={refreshing}              onRefresh={() => setRefreshing(true)}            />          }><SalesAccountFilter /> // <-- Dropdown is rendered but dont render options          {isLoading === true ? (<View style={{marginTop: '50%'}}><Spinner color="#054785" /></View>          ) : (<Content>              ...some content</Content>          )}</ScrollView></Container></>);

In the other screen that the dropdown is implemented in the exactly same way it is working fine. There is no error about it on the console. In the following snippet is the implementation of "SalesAccountFilter".

const styles = StyleSheet.create({  picker: {    maxWidth: 320,    minWidth: 320,    color: 'black',    zIndex: 1000,  },  pickerPlaceholder: {    color: '#bfc6ea',  },});...  return (<DropDownPicker      style={styles.picker}      items={[...accounts]}      defaultValue={null}      placeholder="Select an account . . ."      placeholderStyle={styles.pickerPlaceholder}      containerStyle={{height: 40, width: 320}}      labelStyle={{        fontSize: 14,        textAlign: 'left',        color: '#000',      }}      itemStyle={{justifyContent: 'flex-start'}}      dropDownStyle={{backgroundColor: '#fafafa'}}      onChangeItem={handleSelected}      searchable={true}      searchablePlaceholder="Search account"      searchableError={() => <Text>Not found</Text>}      activeLabelStyle={{color: 'blue'}}    />  );
**Versions:** Ubuntu 20.04lts;Node v15.5.0;React Native Picker 1.9.8;React 17.0.1;Nativebase 2.15.0;React Native 0.63.4;Emulator: Pixel 4 (latest build);

Errors when running command "npx react-native run-android"

$
0
0

C:\Users\lenovo\Desktop\react-native-cli>cd AwesomeProject

C:\Users\lenovo\Desktop\react-native-cli\AwesomeProject>npx react-native run-androidinfo Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.Jetifier found 967 file(s) to forward-jetify. Using 4 workers...info Starting JS server...info Installing the app...Starting a Gradle Daemon, 1 incompatible and 1 stopped Daemons could not be reused, use --status for details

Task :app:processDebugManifest FAILEDError 'C:\Users\lenovo\Desktop\react-native-cli\AwesomeProject\android\app\build\outputs\logs\manifest-merger-debug-report.txt (Access is denied)' while writing the merger report file, build can continue but merging activities will not be documented

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.Use '--warning-mode all' to show the individual deprecation warnings.See https://docs.gradle.org/6.3/userguide/command_line_interface.html#sec:command_line_warnings12 actionable tasks: 2 executed, 10 up-to-date

FAILURE: Build failed with an exception.

  • What went wrong:Execution failed for task ':app:processDebugManifest'.

java.io.FileNotFoundException: C:\Users\lenovo\Desktop\react-native-cli\AwesomeProject\android\app\build\intermediates\manifest_merge_blame_file\debug\manifest-merger-blame-debug-report.txt (Access is denied)

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

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

how do i detect a soft navigation bar in react native apps?

$
0
0

I am working on a react-native app, the problem is that when the soft navigator in android is on, i cannot determine that and the dimensions just changes messing it all up. I have tried "react-native-detect-navbar-android" package but always returns true on real devices and emulators. How do i accurately fix this??

How to access Native database of existing Android project through React Native

$
0
0

I have an android application written in java and I have lots of data in the SQLite database also.Now I want to integrate a module through react Native and existing database access is required in this module.But I am unable to make a connection with the database.

enter code here

"dependencies": {`enter code here`"react": "~16.9.0","react-native": "~0.61.4","react-native-sqlite-storage": "^4.0.0" }

    SQLite.enablePromise(true);    var db = SQLite.openDatabase({name : "mydb", location: 'default'})    .then(res => {      console.log(`Success ${res}`)    })    .catch(err => {      console.log(`Error1 ${err}, ${err.code}`)    });  }```getting error:**TypeError: null is not an object (evaluating 'NativeModules["SQLite"][method]')**

Continuously displaying sensor values in a Text View with react native

$
0
0

In the code below I am trying to get the accelerometer values and timestamp and display them in a Text view. If I comment out the line setVal(timestamp) then the values displayed with console.log({x, y, z, timestamp}) are correct (as expected). However, if I uncomment setVal(timestamp), then the values displayed with console.log eventually become all the same over time.

Not sure what I am doing wrong. I guess that setVal(timestamp) is somehow overriding the values of the variable timestamp. Is there a more correct and better way of doing this?

import React, { useState } from "react";import {View, Text} from 'react-native';import {accelerometer} from 'react-native-sensors';export default function App(props) {  const [val, setVal] = useState(1);  const subscription = accelerometer.subscribe(({x, y, z, timestamp}) => {    console.log({x, y, z, timestamp});    setVal(timestamp);  });  return (<View><Text>Timestamp: {val}</Text></View>  );}

how to implement the arrow alert thing on the notification on instagram

$
0
0

How can I implement this on my app im using react native? or what is it called? Photo for reference. Thank you!!

enter image description here


React Native WebView Android - ERR_INSUFFICIENT_RESOURCES

$
0
0

So I have a WebView in React Native that I want to play a video stored on device.

This is the WebView:

<WebView      originWhitelist={['*']}      style={{flex: 1.0}}      javaScriptEnabled={true}      domStorageEnabled={true}      source={{uri: Platform.OS === 'android' ? 'file://'+ localPath : ''+ localPath }}      mixedContentMode='always'      allowFileAccess={true}      allowFileAccessFromFileURLs={true}      allowUniversalAccessFromFileURLs={true} />

On IOS it works fine. On Android it shows the following:

enter image description here

Is there anything in my power I can do to play the video? I know there are other libraries like react-native-video I should have used from the start but a WebView looked so tempting and easy to use.

App notification setting access in EXPO sdk39

$
0
0

Problem started when i realize that Permissions.askAsync not working as expected.

I find Permissions.askAsync not working as expected and it`s cool solution for ios, but i need it for android! So, i add some extra code for this:

Alert.alert('No Notification Permission','please go to settings and enable notifications permissions manually',        [          { text: 'cancel', onPress: () => console.log('cancel') },          {            text: 'Allow',            onPress: async () => {              if (Platform.OS === 'android') {                await IntentLauncher.startActivityAsync(                  IntentLauncher.ACTION_APP_NOTIFICATION_SETTINGS,                  {                    data: `package:${Application.applicationId}`,                  }                );              }              if (Platform.OS === 'ios') {                Linking.openURL('app-settings:');              }            },          },        ],        { cancelable: false },      );

UPD. construction below works great, but i want to access directly to the APP_NOTIFICATION_SETTINGS.

onPress={() => {            IntentLauncher.startActivityAsync(              IntentLauncher.ACTION_APPLICATION_DETAILS_SETTINGS,              {                data: `package:${Application.applicationId}`,              }            );          }}

Related issue in expo forums https://forums.expo.io/t/opening-device-settings-on-android-using-linking/2059/14

I try to access to the APP_NOTIFICATION_SETTINGS but for some reason i'm getting error like "The app wasn't found in the list of installed apps". Tried it on published project and on standalone (apk) and got the same result. Anyone knows what is the problem?

This merchant is not enabled for Google Pay. [Android, React-Native]

$
0
0

i need to integrate android/google Pay in my app. used react-native-payments for integrate native payment wallet.

Sheet open in type os TEST mode but in release mode give error Like This merchant is not enabled for Google Pay.

already generate merchantId in Play store console and try to run app from beta testing.

how can i enable google pay?? i can't find.

Thanks in advance...

On service start user interface disappears

$
0
0

I'm trying to modify nodejs-mobile module https://github.com/JaneaSystems/nodejs-mobile-react-nativeto start node in a foreground service. I added following method

  @ReactMethod  public void startNodeService() throws Exception {    _instance = this;    if(!_startedNodeAlready) {      _startedNodeAlready = true;      new Thread(new Runnable() {        @Override        public void run() {          waitForInit();          Intent intent = new Intent(getCurrentActivity(), NodeService.class);          intent.setAction("START");          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {            getCurrentActivity().startForegroundService(intent);          }          else {            getCurrentActivity().startService(intent);          }        }      }).start();    }  }

and thats how NodeService class looks like

package com.janeasystems.rn_nodejs_mobile;import android.app.NotificationChannel;import android.app.NotificationManager;import android.app.Service;import android.app.Notification;import android.content.Context;import android.content.Intent;import android.os.Build;import android.os.IBinder;import android.os.PowerManager;import android.util.Log;import androidx.annotation.Nullable;public class NodeService extends Service {    private PowerManager.WakeLock mWakeLock = null;    private boolean mIsServiceStarted = false;    private Thread mNodeThread = null;    static {        System.loadLibrary("nodejs-mobile-react-native-native-lib");        System.loadLibrary("node");    }    public native Integer startNodeWithArguments(String[] arguments, String modulesPath, boolean option_redirectOutputToLogcat);    @Nullable    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        if (intent != null) {            String action = intent.getAction();            switch (action) {                case "START":                    startService();                    break;                case "STOP":                    stopService();                    break;                default:                    break;            }        }        return START_STICKY;    }    @Override    public void onCreate() {        super.onCreate();        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {            startForeground(11470, createNotification());        }    }    private void startService() {        if (mIsServiceStarted) return;        final String nodeDir = getApplicationContext().getFilesDir().getAbsolutePath() +"/nodejs-project";        final String modulesDir = getApplicationContext().getFilesDir().getAbsolutePath() +"/nodejs-builtin_modules";        mIsServiceStarted = true;        mWakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NodeService::lock");        mWakeLock.acquire();        mNodeThread = new Thread(new Runnable() {            @Override            public void run() {                startNodeWithArguments(new String[]{"node", "-e","myScript.js"                        },                        nodeDir +":" + modulesDir,                        true                );            }        });        mNodeThread.start();    }    private void stopService() {        try {            if (mWakeLock != null) {                if (mWakeLock.isHeld()) {                    mWakeLock.release();                }            }            stopForeground(true);            stopSelf();        } catch (Exception e) {            //something went wrong;        }        mIsServiceStarted = false;    }    public Notification createNotification() {        String notificationChannelId = "Server Channel";        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);            NotificationChannel channel = new NotificationChannel(notificationChannelId, "server notifications channel", NotificationManager.IMPORTANCE_HIGH);            channel.setDescription("Server Channel");            channel.enableLights(false);            channel.enableVibration(false);            channel.setSound(null, null);            channel.setShowBadge(false);            notificationManager.createNotificationChannel(channel);        }        Notification.Builder builder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? new Notification.Builder(this, notificationChannelId) : new Notification.Builder(this);        return builder                .setContentTitle("Server")                .setContentText("server is running")                .setPriority(Notification.PRIORITY_HIGH)                .build();    }}

When service is started and notification is displayed whole interface disappears. I can't figure why this is happening

React Native Rendering Image borderRadius in iOS

$
0
0

Images are rendered in different aspects in ios and android using image component from react-native. I’m trying to display image with 45 degree angle cutoff every corner.

I have tried to use cover, contain and center of the resizeMode prop cover fills the image inside the view giving the 45 degree cut but crops either width or height.

Center does not crop the image but if the image isn’t similar ratio as the view the 45 degree angles aren’t cut of the image, Android does this well though.

<View style={(this.state.controlsDisplayed) ? styles.flexLR : styles.flexLRBlack}><View style={{flex: (Platform.OS === ‘ios’) ? 0.85 : 0.5}} /><View style={styles.imageWrapView}><Image source={{uri: ‘file://’+ item.photoLeft}} key={“TDVIEW”} resizeMode={(Platform.OS == ‘ios’) ? ‘cover’ : ‘center’} style={styles.floatingImagePartView} /></View><View style={{flex: (Platform.OS === ‘ios’) ? 0.85 : 0.5}} /></View>

Want to get uncropped images on ios that have corners cut of by 45 degrees. Same as is in the android images. Here are images from android device that are rendered correctly.

android1 cutoff

android1 image

Here are the images rendered on ios using center and cover

android1 cutoff

This is rendered using contain on ios

android1 cutoff

android1 image

How can I get the images rendered with 45 degree cutoff on ios device as it is on an android device?

React Natice WebView Crashed

$
0
0


I have an application build with Expo Project. I try to implement a feature using WebView. All the web can load properly from the WebView. But, inside the WebView page, we have a download feature. Whenever I try to click the download button the application crash immediately. I don't know why because I can't see any error message in the terminal and Expo didn't show up any error message as well. The app just crashed. Is there any way to handle errors like this from React Native WebView guys? So at least the app won't be crashed.
P.S: it only happens in Android only.

Accessing a variable present inside script tag in react-native-webview

$
0
0

My goal here is to insert an image in Quill editor in react-native-webview component as shown below. For which I need access to the quill variable in the script tag:

<WebView    originWhitelist={['*']}    ref={(r) => setWebref(r)}    javaScriptEnabled={true}    source={{      html: `<head><link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet"><script src="https://cdn.quilljs.com/1.3.6/quill.js"></script></head><body><div id="editor" >${content}</div></body><script>               var toolbarOptions = [[ 'bold', 'italic',],];              var quill = new Quill('#editor', {              modules: {                toolbar: toolbarOptions              })</script>`,    }}  />

When I try to run following snippet outside webview in react-native, nothing is happening

  const url = `https://...`;  const code = `const range = window.quill.getSelection();               window.quill.insertEmbed(range.index, 'image', ${url});              `;  webref.injectJavaScript(code);

But, when I try to run following snippet outside webview in react-native, I am getting the expected result.

 const snippet = `document.body.style.backgroundColor = 'blue';                  true;                  `; webref.injectJavaScript(snippet);

npx react-native run-android: E/Device: Error during Sync: EOF

$
0
0

I am trying to run react native app to my real android device.I checked my device before running

adb devicesList of devices attached3357425441473098        device

I started with

npx react-native start

and in other console

npx react-native run-android

But got an error..

Task :app:installDebug FAILED                                                                                                                                                     10:25:40 V/ddms: execute: running am get-config                                                                                                                                     10:25:40 V/ddms: execute 'am get-config' on '3357425441473098' : EOF hit. Read: -1                                                                                                  10:25:40 V/ddms: execute: returning                                                                                                                                                 Installing APK 'app-debug.apk' on 'SM-G960U - 9' for app:debug                                                                                                                      10:25:40 D/app-debug.apk: Uploading app-debug.apk onto device '3357425441473098'10:25:40 D/Device: Uploading file onto device '3357425441473098'10:25:40 D/ddms: Reading file permision of /home/user/react-native/awesomeProject/android/app/build/outputs/apk/debug/app-debug.apk as: rw-rw-r--                10:25:40 D/ddms: read: channel EOF                                                                                                                                                  10:25:40 E/Device: Error during Sync: EOF                                                                                                                                           Unable to install /home/user/react-native/awesomeProject/android/app/build/outputs/apk/debug/app-debug.apk                           com.android.ddmlib.InstallException: EOF      

And right after that error. I lost my device connection.

adb devices

shows nothing..

and at the bottom of stacktrace I see this error also

Caused by: java.io.IOException: EOF        at com.android.ddmlib.AdbHelper.read(AdbHelper.java:862)        at com.android.ddmlib.SyncService.doPushFile(SyncService.java:712)        at com.android.ddmlib.SyncService.pushFile(SyncService.java:406)        at com.android.ddmlib.Device.syncPackageToDevice(Device.java:988)        at com.android.ddmlib.Device.installPackage(Device.java:902)

FAILURE: Build failed with an exception.

* What went wrong:Execution failed for task ':app:installDebug'.> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: EOF* 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 10s    at checkExecSyncError (child_process.js:629:11)    at execFileSync (child_process.js:647:13)    at runOnAllDevices (/home/user/react-native/newProject/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:39)    at buildAndRun (/home/user/react-native/newProject/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:158:41)    at then.result (/home/user/react-native/newProject/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)

My device is us samsumg galaxy s9. It was working when I use Expo sdk. What is my problem?

react-native : 0.61.5

Weird thing is that it works first execution after computer boot. then I tried reconnect phone, and it pops up again.

Horizontally and vertically scrollable layout in react native

$
0
0

I am trying to configure table grid layout in react native which could be scrollable horizontally and vertically.

By table grid layout I mean the layout similar to html table/tr/td: all views in the same row should have the same height and all views in the same column should have the same width.

The height of the row should be selected based on the height of the biggest view in the row.The width of the column should be selected based on the width of the biggest view in the column.

I've started with horizontal scrolling.This is what I've done:https://snack.expo.io/@grekonstudio/01_initialWhile it looks fine for me in the browser, on my device in looks this way:

enter image description here

The biggest column takes as much space as it needs and the rest of the space is shared between other columns. But it is done for each row independently, so columns border floats. Ideally, I want Row 1, Col 1 and Row 2, Col 1 to be the same size as Row 3, Col 1. That does not work as they and in different rows.

Well, obvious idea is to switch to column base layout, right:https://snack.expo.io/@grekonstudio/04_column_basedAgain, in the browser, it looks different. On the device it looks this way:

enter image description here

On the first look, this is exactly what I want! But apparently, it just moves the problem to another dimenstion. Let's make one View higher than the others, add a vertical ScrollView and we are losing row layout now:https://snack.expo.io/@grekonstudio/05_same_problem

enter image description here

You can see the bigger cell takes all space and the rows are not having the same size anymore :(

Additionally, I tried two more things:

Getting device height and width and fixing the size of the scroll view contentContainerStylehttps://snack.expo.io/@grekonstudio/03_fixed_widthIn this case 'flex: 1' works as it works without a scroll view: splitting it to equal size boxes, while I want rows and cols to be adjusted by contentAnother disadvantage is hardcoding width: 2 * screenWigth as e.g. for small content I might not need 2 screen width, I might need 1.5 or 1.2 only. It would also not work in portrait easlity.

I've also tried using the DataTable component https://callstack.github.io/react-native-paper/data-table.html, but when added to horizontal scroll view it fails to keep table layout the same way as in my first image: cells in the same column have different width.

Does anyone have a solution for the above?

React-Native Talkback reads component accessibilityRole in wrong language

$
0
0

I have a React-Native application where we want to support Talkback in Finnish and English. When using Google's Text to Speech module in Finnish everything else works fine, except "button" is read as "button" instead of Finnish equivalent "Painike". On iOS it also works fine. I'm testing on Samsung A40. Samsung Text to Speech doesn't support Finnish at all.

So for example, when I press button that reads "Paina minua" it reads "Button, paina minua", instead of "painike, paina minua". This only happens in the application I am developing. It also reads Image components as Images instead of in Finnish. Probably other components too.

In apps like Discord, Facebook, Instagram etc. buttons are read correctly as "Painike" instead of "button".

What can I do to make Talkback work correctly in our application?

Example button definition:

<TouchableOpacity  onPress={onPress}  accessibilityRole="button"><Text>Paina minua</Text></TouchableOpacity>

react-native: 0.63.2

Is it possible to use ExcelJS in React Native?

$
0
0

I am trying to create an excel sheet from React Native mobile application. I have tried using xlsx to generate excel. But it is not supporting the styling excel sheet. Is it possible to use ExcelJS in React Native?

React native TouchableOpacity onPress not working on Android

$
0
0

TouchabelOpacity works fine on iOS but the onPress method does not work on Android for me.

My react-native version: 0.57.4

My code:

const initDrawer = navigation => (<TouchableOpacity    style={{ left: 16 }}    onPress={() => onPressDrawerButton(navigation)}><Ionicons name="ios-menu" color="white" size={30} /></TouchableOpacity>);
Viewing all 29551 articles
Browse latest View live


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