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

what's this weird : JSON Parse error: Unexpected identifier "Tunnel"

$
0
0

i was trying to fetch some data from the server to display in the react native app. it was worked before but i don't know what happened after, i added a console.log in the catch of fetch.. it showing me error like

JSON Parse error: Unexpected identifier "Tunnel" - node_modules/promise/setimmediate/core.js:37:14 in tryCallOne - node_modules/promise/setimmediate/core.js:123:25 in - ... 8 more stack frames from framework internals

fetch(`${this.props.baseUrl}/products?page=${this.state.page}&per_page=10`,{    method:"get",    headers:{        AUTH_TOKEN: this.props.AUTH_TOKEN    }}).then(res=>res.json()).then(data=>{    if(data.success==true){        this.page++;        this.props.toggleLoading();        this.props.loadProducts(data.products);    }}).catch(err=>console.log(err)); //error here ..i dont know why that's throwing this kinda error 

How can i emit data for app when invoking it from inactive to foreground state [Android ReactNative]

$
0
0

I have trouble with passing data from one device to another.Scenario:I make push (data-only) from A device to B device.B device receive push and call NativeModules method "invokeApp({ data: "someValue" })"

In my native module i write next code:

    private static ReactApplicationContext reactContext;    public static final String LOG_TAG = "RNInvokeApp";    private static Bundle bundle = null;    public RNInvokeApp(ReactApplicationContext context) {        super(context);        reactContext = context;    }    @Override    public String getName() {        return "RNInvokeApp";    }    @ReactMethod    public void invokeApp(ReadableMap params) {        String packageName = reactContext.getPackageName();        Intent launchIntent = reactContext.getPackageManager().getLaunchIntentForPackage(packageName);        String className = launchIntent.getComponent().getClassName();        try {            Class<?> activityClass = Class.forName(className);            Intent activityIntent = new Intent(reactContext, activityClass);            activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent            .FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);            reactContext.startActivity(activityIntent);        } catch(Exception e) {            Log.e(LOG_TAG, "Class not found", e);            return;        }          WritableMap paramsData = Arguments.createMap();          paramsData.putString("eventProperty", "someValue");          reactContext          .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)          .emit("appInvoked", paramsData);      }   }

If device B in background or foreground, this works perfectly. But when device B in killed state, i have no any emitting in device B

const eventEmitter = new NativeEventEmitter(NativeModules.RNInvokeApp);eventEmitter.addListener('appInvoked', (event) => {  console.log(event.eventProperty);});

React native queries GPS coordinates and gives timeout

$
0
0

We have the next problem:We are consulting the gps location in order to get a list that contains only those that are close in a radius, but when consulting the GPS it gives us timeout after at leat 40 seconds of waiting.The problem especially occurs in Android with a Xiaomi Redmi 8 in industrial environments, with less connection than usual or on the move, they don´t have access to LTE all the time.We use the library @ react-native-community / geolocation or navigation.positionCan you help us with any other library or strategy to obtain GPS position that does not consists in the gps wacthing changes on its position all the time? something like getting it on the background..

Code

Geolocation.getCurrentPosition(                    position => {                        // process the position                    },                    error => {                        console.log(error);                    }, {                        timeout: 40000,                        maximumAge: 0                    }                );

How to open new screen in with onPress in React Native?

$
0
0

I dont have any errors but I still cant open screen that I want. I find out and I think I need navigation but I dont know how to implement it. Here is my FlatList item:

let categories = [         {            screenName : Player,            name : "Category 1",            img : require("../Assets/Slika.jpg"),        },

Here is TouchableOpacity with onPress

return (<View style={styles.container}><FlatList            data={categories}            showsHorizontalScrollIndicator={false}            numColumns={categories.length / 5}            showsVerticalScrollIndicator={false}            keyExtractor={(item, index) => index.toString()}            renderItem = {({item, index}) => {                return (<TouchableOpacity onPress={() => item.screenName}><Surface style={styles.surface}><ImageBackground                    source={item.img}                     style={styles.img}                    blurRadius={0.5}><Icon name="music" color="#fff" size={22}/><Text style={styles.name}>{item.name}</Text></ImageBackground></Surface></TouchableOpacity>                );            }}        /></View>

Here is some code for function I get:

import { useNavigation } from '@react-navigation/native';...export default function ClassName() {const navigation = useNavigation();function navigateTO(pageName) { navigation.navigate(pageName);}<TouchableOpacity onPress={navigateTO(item.screenName})>

React Native App Not Installed Error

$
0
0

I'm testing out react native and can run the dev server fine on an emulator. When I go to build the apk to test on a real device, I get an

Application not installed error

System

  • My Device is Android 5.1.1
  • Emulator is Android 4.4
  • React Native 16

Steps to build apk

  1. keytool -genkey -v -keystore my-app-key.keystore -alias my-app-alias -keyalg RSA -keysize 2048 -validity 10000
  2. react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
  3. cd android && ./gradlew assembleRelease
  4. Got apk app-release-unsigned.apk

Is there anything I am missing and is the generated file supposed to be unsigned.apk ?

Emulator process getting killed with Android Studio?

$
0
0

I am trying to start the emulator from Android Studio. It opens for seconds and then shut off and appears this error:

The emulator process for AVD Pixel_3 was killed.enter image description here

I think I've installed Pixel 3 emulator correctly and I have these SDK tools installed:

  • Android SDK Build-Tools 30

  • Android Emulator

  • Android SDK Platform-Tools

  • Intel x86 Emulator Accelerator (HAXM installer)

SDK Platform: Android 10.0+ (R)

I also already tried doing these steps but didn't work for me:Go to: Tools > Android > AVD ManagerPress the "edit" (pencil) icon next to your AVDChange "Graphics" to "Software".

Any hints or ideas? Thank you in advance!

Change color of statusBar in splashScreen react-native android

$
0
0

enter image description here

I try to add a splash screen to a RN app. As you can see in the gif the status bar color is changing to black while the splash screen is on, but i can't find the problem exactly.I have followed this tutorial to implement the splash screen: Add splash screen to RN appPlease find here the code i added to android studio:

in AndroidManifest.xml =>

<activity            android:name="MainActivity"            android:label="@string/app_name"            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"            android:windowSoftInputMode="adjustResize"            android:launchMode="singleTop"            android:screenOrientation="portrait"            android:exported="true"            /><activity            android:name=".SplashActivity"            android:theme="@style/SplashTheme"            android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /><action android:name="android.intent.action.DOWNLOAD_COMPLETE"/></intent-filter></activity>

in styles.xml =>

<resources><!-- Base application theme. --><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><!-- Add the following line to set the default status bar color for all the app. --><item name="android:statusBarColor">@color/mdcGreen</item><!-- Add the following line to set the default status bar text color for all the app    to be a light color (false) or a dark color (true) --><item name="android:windowLightStatusBar">false</item><!-- Add the following line to set the default background color for all the app. --><item name="android:windowBackground">@drawable/background_splash</item></style><!-- Adds the splash screen definition --><style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar"><item name="android:statusBarColor">@color/mdcGreen</item><item name="android:background">@drawable/background_splash</item></style></resources>

in drawable/background_splash.xml =>

<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"><item        android:drawable="@color/mdcGreen"/><item        android:width="200dp"        android:height="200dp"        android:drawable="@mipmap/mdc"        android:gravity="center" /></layer-list>

in layout/launch_screen.xml =>

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical"    android:background="@drawable/background_splash"    android:statusBarColor="@color/mdcGreen"></LinearLayout>

THANKS!

react-native-background-timer inconsistently works on Android for recording audio

$
0
0

I am using BackgroundTimer from react-native-background-timer in a React native project for Android.

I want a user to be able to record audio after a set duration (e.g. record for 5 minutes after 30 minutes).

The issue I have is that it works "sometimes". It seems the OS is often killing the process - especially if the time to execute is longer.

Code extract:

import BackgroundTimer from 'react-native-background-timer';...// Start a timer that runs once after X millisecondsconst timeout1 = BackgroundTimer.setTimeout(() => {    // Should work when when app is the the background    this.onStartRecord();    const timeout2 = BackgroundTimer.setTimeout(() => {        this.onStopRecord();        BackgroundTimer.clearTimeout(timeout2);    }, millisRecording);    // Clear first timeout    BackgroundTimer.clearTimeout(timeout1);}, millisUntilRecordMoment);

Thes rest of the code is here: https://github.com/bentaly/listen/blob/master/App.tsx

I have also tried building this in Expo previously which didn't work.

Is there anyway to guarantee this operation will work?


backAndroid/backHandler working for every screen--React Native

$
0
0

I have enabled backandroid to show logout alert in home screen. Problem is even though screen navigated away from home screen. still Logout alert coming. basic back navigation is also disabled.

HomeScreen.js

 componentWillMount() {    BackHandler.addEventListener('hardwareBackPress', this._handleback);}componentWillUnmount() {    //Forgetting to remove the listener will cause pop executes multiple times    BackHandler.removeEventListener('hardwareBackPress', this._handleback);} _handleback = () => {    Alert.alert(i18N.t('alertHeader'), i18N.t('logoutqHeader'), [        {            text: i18N.t('yes'), onPress: () => { this.props.navigation.navigate('login'); }        },        { text: i18N.t('cancel'), onPress: () => { return true; }, style: 'cancel' },    ], { cancelable: false });    return true;};

I want to show logout alert only in home screen. In other screens I want to follow basic back navigation. Please let me know how to solve this.

How to prevent redirecting when using react-native-webview on Android

$
0
0

I want to prevent redirecting to new page in react-native-webview.Instead of redirection, I want to open new webview modal and open url at there.

Is it possible way to do this?

In IOS, using stopLoading works fine but it is not working on Android,

onNavigationStateChanged(navState) {    if(navState.canGoBack)    {        this._webView.stopLoading();        if(navState.url.indexOf('newWebViewPage') !== -1)        {            this.props.navigation.navigate('WebViewModal',{'url':navState.url,'title':navState.url            })            return false;        }        else        {            return true;        }    }}render() {    let headers = {'Authorization':'Basic '+ btoa(NetworkUtils.USERNAME +":"+ NetworkUtils.PASSWORD),'Content-Type':'multipart/form-data',    }    return (<WebView            source={{ uri: this.props.url, headers:headers }}            bounces={false}            javaScriptEnabled={true}            onMessage={this.onMessage.bind(this)}            injectedJavaScript={injectedJavascript}            ref={(webView) => { this._webView = webView; }}            style={[styles.webview,this.props.style]}            startInLoadingState={false}            useWebKit={true}            onNavigationStateChange={this.onNavigationStateChanged.bind(this)}            onLoadEnd={this.props.onLoadEnd?this.props.onLoadEnd:()=>{}}            mixedContentMode={'compatibility'}        />    );}

Please help!!

How to scroll parent ScrollView while child is moving in it using PanResponder

$
0
0

I am looking for an option to build this functionality in react native.

enter image description here

I have added PanResponder inside a scroll view but the problem is when I drag an item in screen scroll view does not scroll. So is there any option available in react-native to drag and scroll at the same time to achieve the same view.

I get stuck in loading screen after building in expo

$
0
0

Usually when i login either with google or Facebook in my app i get automatically redirected to the home menu that is a map but after i build and ran my app i get stuck in loading every-time after i log in

How can I exclude/delete flavour specific asset files through Gradle?

$
0
0

In my React Native app, I have two flavours. Each flavour has some image and video assets that are only used in that flavour.

To reduce the size of the APK, I would like to exclude unnecessary assets prior to, or during build time.

What would be the best way to accomplish this?

I did try using aaptOptions, along the lines of the below, but this never worked for me:

aaptOptions {'/folder:*.jpg:*.png'        ignoreAssetsPattern "!/"+projectName+":*.mp4:"}

I previously had the following task at the bottom of my build.gradle file:

task deleteOtherFlavourAssets(type: Delete) {    description = 'Deleting non $projectName assets'    delete fileTree("src").matching {        exclude "**/app_assets_$projectName**"        include "**/app_assets_**"    }}preBuild.dependsOn deleteOtherFlavourAssets

This did the job for a while, however it stopped working a few months ago. I've not been able to get it working again.

I should mention that when running the above task as a copy (instead of delete), the right files are duplicated into this directory.

task otherFlavourAssets(type: Copy) {    description = 'Copying non $projectName assets to temp directory'    copy {        from fileTree("src").matching {            exclude "**/app_assets_$projectName**"            include "**/app_assets_**"        }        into 'tempAssetStore'    }}

So it is very possible that a subsequent task is copying/merging the superfluous assets back in, or perhaps a cache issue.

React Native Android cannot load html file from local

$
0
0

I would like to load a local html file in my React Native App. Its works in IOS but failed in Android. Here I my code:-

<WebView          originWhitelist={['*']}          source={Platform.OS === 'android' ? { uri: 'file:///android_asset/index.html' } : require('../screens/index.html')}          startInLoadingState={true}          />

Here is my local html file path.

enter image description here

I have no idea where should I configure in order to get it works...Please help. Thank you.

React Native Image resizeMode='contain' distorts some images on Android device and emulator

$
0
0

The resizeMode='contain' in the React Native Image component distorts some images on Android devices and emulators. For most images, it creates a distorted line in the PNG image background. I've tried many different images, also tried resizing them, but nothing fixes the distorted coloured line.Note: All those images look fine on iOS.

Andoid Nexus 10 API 28 emulator

Amazon Fire Tablet 8th Gen.

iPad Pro (11-inch) simulator

Here is my code for the Image component. I am trying to create a grid view of images for a pizza app.

<View style={{            flex: 1,            flexDirection: 'column',            justifyContent: 'center',            alignItems: 'stretch',          }}>            {/* ==================================First Row ===================================*/}<View style={{ height: 600, flexDirection: 'row', backgroundColor: 'transparent', marginVertical: 10 }}><View style={{                flex: 1, flexDirection: 'column', marginHorizontal: 20,                borderWidth: 2, borderColor: 'lightgray', borderRadius: 10              }}><Image                  style={{                    flex: 1, height: undefined, width: undefined, borderColor: 'black', borderWidth: 1,                  }}                  source={require('./Images/pizza5.png')}                  resizeMode='contain'></Image><Text style={{ fontSize: 20, marginVertical: 5, marginHorizontal: 10 }}>Pizza 1</Text><Text style={{ fontSize: 17, marginTop: 15, marginBottom: 10, marginHorizontal: 10 }}>$10.99</Text></View><View style={{                flex: 1, flexDirection: 'column', backgroundColor: 'transparent',                borderWidth: 2, borderColor: 'lightgray', borderRadius: 10, marginRight: 20,              }}><Image                  style={{                    flex: 1, height: undefined, width: undefined, borderColor: 'black', borderWidth: 1                  }}                  source={require('./Images/pizza1copy.png')}                  resizeMode='contain'></Image><Text style={{ fontSize: 20, marginVertical: 5, marginHorizontal: 10 }}>Pizza 2</Text><Text style={{ fontSize: 17, marginTop: 15, marginBottom: 10, marginHorizontal: 10 }}>$10.99</Text></View></View></View>

Show a component in all screens with React-Navigation - React Native

$
0
0

I want to have a component like button (or react-native-action-button precisely) to be shown in each screen using React Navigation.

Does React Navigation has any option in inside Routes to implement it once and use everywhere?

Note: I don't want to import Component in each .js class and use it in render.

Reference -> Like this in app's each screen.Floating Action Button Reference

Meterial Top Tab Navigator

$
0
0

In my project, when i am using Material Top Tab 'activeTintColor' is not working in ios. Please help me..Thanks in advance.

import React from 'react'import { View, Text } from 'react-native'import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs'import { Icon } from 'react-native-vector-icons/AntDesign'import { NavigationContainer } from '@react-navigation/native'

const Home = () => { return ( Home! )}

const Profile = () => { return ( Profile! )}const Chat = () => { return ( Chat! )}

const Notification = () => { return ( Notification! )}

const Tab = createMaterialTopTabNavigator();const TopTabNavigatorDemo = () => { return (

<Tab.Screen                name='Home'                component={Home}                options={{ tabBarLabel: 'Home' }} /><Tab.Screen name='Profile' component={Profile} options={{ tabBarLabel: 'Profile' }} /><Tab.Screen name='Chat' component={Chat} options={{ tabBarLabel: 'Chat' }} /><Tab.Screen name='Notification' component={Notification} options={{ tabBarLabel: 'Update' }} /></Tab.Navigator></NavigationContainer>)

}

export default TopTabNavigatorDemo

react-native 0.60+ code-push: An update check must include a valid deployment key

$
0
0

I don't know why this error occurs, May I ask if there is a problem with my configuration?

Use

react-native 0.61.5

react-native-code-push 6.2.1

error message:

Time    Tag Message15:46:21.152    ReactNativeJS   [CodePush] Sync already in progress.15:46:21.369    ReactNativeJS   [CodePush] Checking for update.15:46:21.427    ReactNativeJS   [CodePush] Reporting binary update (3.0.5)15:46:30.692    ReactNativeJS   [CodePush] An unknown error occurred.15:46:30.692    ReactNativeJS   [CodePush] 400: An update check must include a valid deployment key - please check that your app has been configured correctly. To view available deployment keys, run 'code-push deployment ls <appName> -k'.15:46:30.704    ReactNativeJS   [CodePush] Report status failed: {"appVersion":"3.0.5"}

This is my configuration:

in android\app\src\main\java\com\***\***\MainApplication.java

+ import com.microsoft.codepush.react.CodePush;+     @Override+     protected String getJSBundleFile() {+       return CodePush.getJSBundleFile();+     }    @Override    protected List<ReactPackage> getPackages() {      @SuppressWarnings("UnnecessaryLocalVariable")      List<ReactPackage> packages = new PackageList(this).getPackages();+      for (ReactPackage rp : packages) {+        if (rp instanceof CodePush) {+          packages.remove(rp);+          break;+        }+    }+      packages.add(new CodePush(BuildConfig.CODEPUSH_KEY, getApplicationContext(), BuildConfig.DEBUG));      return packages;    }

in android\app\build.gradle

    buildTypes {        debug {            signingConfig signingConfigs.debug+            buildConfigField "String", "CODEPUSH_KEY",  '""'        }        release {            signingConfig signingConfigs.release            minifyEnabled enableProguardInReleaseBuilds+            buildConfigField "String", "CODEPUSH_KEY", '"******************"'            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"        }        releaseStaging {+            buildConfigField "String", "CODEPUSH_KEY",  '"*******************"'        }

in android\app\src\main\res\values\strings.xml

+<string name="appCenterCrashes_whenToSendCrashes" moduleConfig="true" translatable="false">DO_NOT_ASK_JAVASCRIPT</string>+<string name="appCenterAnalytics_whenToEnableAnalytics" moduleConfig="true" translatable="false">ALWAYS_SEND</string>+<string moduleConfig="true" name="CodePushDeploymentKey">************8</string>

in app.js

+ import codePush from 'react-native-code-push';+ @codePushclass App extends React.PureComponent {  componentDidMount() {+      codePush.sync({+        updateDialog: true,+        installMode: codePush.InstallMode.IMMEDIATE,+      });  }

ACRA Mailer not giving me share file as window in Android 10

$
0
0

I am using ACRA 5.5.1 in React Native 0.61.2. I am using Dailog + Mailer feature to send the crash reports.

@AcraCore(buildConfigClass = BuildConfig.class,    reportFormat = StringFormat.JSON)@AcraMailSender(mailTo = "email",   resSubject = R.string.acra_mail_subject,   reportFileName = "ErrorReport",   reportAsFile = true)@AcraToast(resText = R.string.acra_toast_text)public class MainApplication extends Application implements ReactApplication {@Overrideprotected void attachBaseContext(Context base) {    super.attachBaseContext(base);    CoreConfigurationBuilder builder = new CoreConfigurationBuilder(this)            .setBuildConfigClass(BuildConfig.class)            .setReportFormat(StringFormat.JSON);    builder.getPluginConfigurationBuilder(ToastConfigurationBuilder.class)            .setResText(R.string.acra_toast_text);   builder.getPluginConfigurationBuilder(MailSenderConfigurationBuilder.class)           .setMailTo("email")           .setResSubject(R.string.acra_mail_subject)           .setReportFileName("ErrorReport")           .setReportAsFile(true);    ACRA.init(this, builder);}}

Now, when I am using the APK in android 5.0, everytime my app crashes it open up a small window at bottom to share the report via email. The image bellow shows the share option popping up in Android 5.0, Phone is Sony Xperia E2362.

enter image description here

But when I am using the APK in Android 10, phone xiaomi poco f1. It doesn't show me any window to share the file.But right after I install my app, xiaomi scans the app and gives one option to open it. And when I open the app from that window I get that share report via email popup, after the app crashes.But not when I normally open my app from app menu.Bellow image shows the app scanning window which shows an option to open app and the second image which shows the share report via email when I use scanning window to open app.

enter image description hereenter image description here

I don't know what am I missing. Please help.

Recorded AAC audio in Android, won't play in iOS devices

$
0
0

AAC audio recorded in Android is not playing in iOS devices. Here is the code example how we are recording the audio in Android device. When we try to play that audio in iOS device using react-native-sound, It won't play and shows error like this.

Failed to load the soundand iOS exception read as below.

Objectcode: "ENSOSSTATUSERRORDOMAIN1937337955"domain:"NSOSStatusErrorDomain"message: "The operation couldn't be completed. (OSStatus error 1937337955.)"nativeStackIOS: Array[17]userInfo: Object__proto__: Object

AudioRecorder.prepareRecordingAtPath('/path/to/audio/test.aac', {        SampleRate: 22050,        Channels: 1,        AudioQuality: "Low",        AudioEncoding: "aac",        AudioEncodingBitRate: 32000});

We are using RN 0.41 and react-native-audio 3.2.1

DId anyone face similar issue? let me know if there is any misconfiguration.

Viewing all 28479 articles
Browse latest View live


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