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

Android Native to React Native bridge

$
0
0

I've been searching on how to make a bridge between React Native and Android Native code for a while, but I still don't quite get it. I've read the documentation here , but I don't quite understand it.What I want to do is, I want to build an apps that utilize push notification, but since I need to push message to China, I can't use GCM (thanks to the great firewall), so I use another third party push SDK.

I've managed to integrate the push into my apps (resulting a console.log() message whenever I push something), the next step is I want to re-route it to certain page

Any help will be appreciated :)


How to set a timer in React native for Android

$
0
0

Setting timers for multiple minutes isn't handled properly in React Native on Android: it keeps the Timing module awake instead of relying on the system waking us up when the timer should go off.

Note:Same timer is working fine in iOS build.

React Native Geolocation Timed Out

$
0
0

I use geolocation to get the current location of users in my project. but I get the Timed Out Error error.

{TIMEOUT: 3, POSITION_UNAVAILABLE: 2, PERMISSION_DENIED: 1, message: "Location request timed out", code: 3}

API 28 android phone success,API 21 android phone success,API 23 android phone time out error.

All permission granted.

   try{            Geolocation.getCurrentPosition(                position => {                    const initialPosition = JSON.stringify(position);                    this.setState({                        firstLat: position.coords.latitude,                        firstLng: position.coords.longitude,                    });                    this.getLocation(position.coords.latitude, position.coords.longitude);                    this.setState({                        isLoading:true                    })                },                error => console.log(error),                {enableHighAccuracy: true, timeout:10000, maximumAge:1000},            );        }catch (e) {            console.log(e)        }

AndroidManifest.xml

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

thank you.

How to detect hold and fastforward event in react native TVEventHandler

$
0
0

I am new to React Native. I want to know how can implement press and hold event for seek.I am able to get fastForward and press right events in React native layer by using below code.

_enableTVEventHandler() {    this._tvEventHandler = new TVEventHandler();    this._tvEventHandler.enable(this, function(cmp, evt) {      if (evt && evt.eventType === 'right') {        cmp.setState({board: cmp.state.board.move(2)});      } else if(evt && evt.eventType === 'up') {        cmp.setState({board: cmp.state.board.move(1)});      } else if(evt && evt.eventType === 'left') {        cmp.setState({board: cmp.state.board.move(0)});      } else if(evt && evt.eventType === 'down') {        cmp.setState({board: cmp.state.board.move(3)});      } else if(evt && evt.eventType === 'playPause') {        cmp.restartGame();      }    });  }

Not able to get the hold fastforward or hold and right event to detect seek event. I am not sure it if its possible in RN layer. If not then how can i do the same in Android layer.

Thanks in advance

Easiest way to build both React-Native app (iOS & Android) and a PWA

$
0
0

what is the easiest way to build both React-Native app (iOS & Android) and a PWA ? Shall I start with building PWA using React and then copy the codes to React-Native SDK or vice versa ? Does the 'Controller' part of MVC philosophy differ between React-Native App and PWA ?

`componentDidMount()` function is not called after navigation

$
0
0

I am using stackNavigator for navigating between screens. I am calling two API's in componentDidMount() function in my second activity. When i load it first time, it gets loaded successfully. Then i press back button to go back to first activity. Then, if i am again going to second activity, the APIs are not called and I get render error. I am not able to find any solution for this. Any suggestions would be appreciated.

react-native View config getter callback for component 'rect' must be a function (received 'undefined')

$
0
0

I am trying to integrate a package known as react-native-simple-maps. I have attached the code below.

import React, { Component } from "react"import ReactDOM from "react-dom"import { ComposableMap, ZoomableGroup, Geographies, Geography } from "react-simple-maps"import {    View} from 'react-native'export default class PlotlyGlobal extends React.Component {    render() {        return (<View><ComposableMap><ZoomableGroup><Geographies geography={"./india.topo.json"}>                            {(geographies, projection) =>                                geographies.map(geography => (<Geography key={geography.id} geography={geography} projection={projection} />                                ))                            }</Geographies></ZoomableGroup></ComposableMap></View>        )    }}

Not able to display the map. Please do guide me. I am new to React-Native.

Facing delay in response from the hub using SignalR ReactNative in ANDROID

$
0
0

Error: Setting timers for multiple minutes isn't handled properly in React Native on Android: it keeps the Timing module awake instead of relying on the system waking us up when the timer should go off.

Note:Same timer is working fine in iOS build.


react-native-background-task only shows 'Job is running'

$
0
0

I am using react-native-background-task for my app and it's working fine. But in some devices, it only shows BackgroundTask: Job is running in console and not executing the job I have assigned to do. Any suggestion?

How to change color of a Like button on react native with galio

$
0
0

I want to implement a like button that changes it's icon color when it's liked and that can be disliked reverting the color change and like stored in my app. I am using react Native with expo and the galio frameworks This is my attempt:

function like_quote(_this) {    _this.setState( {iconColor: theme.COLORS.THEME })    //_this.iconColor= theme.COLORS.THEME //I also tried this    Alert.alert('Like!') //this is supposed to be where I store the like for my app}

this inside the render()

...<Button              onlyIcon              icon="heart"          key="like"              iconFamily="font-awesome"              iconSize={theme.SIZES.BASE}              iconColor={'#ffbbbb'}//theme.COLORS.THEME              color="transparent"              style={{ marginRight: theme.SIZES.BASE }}              onPress={() => like_quote(this)}            />,    ...

Though it does nothing to the button. The Alert works fine but the icon color doesn't change.

react native android keyboard empty space

$
0
0

I am trying to fix a problem we are having with the keyboard on android. Due to react-native-gifted-chat, we have to use android:windowSoftInputMode="adjustResize" instead of adjustPan. The problem is, that the chat breaks without adjustResize and all the other stuff (e.g. some textfields in a form) break without adjustPan. I also tried adjustResize|adjustPan, adjustPan|adjustResize and tried to use KeyboardAvoidingView on the Form components, but nothing seems to work. Here is how it looks like when using adjustResize without any KeyboardAvoidingView. It creates some not-clickable grey area above the keyboard. Note that there is no way around adjustResize due to the chat...

Thanks in advance!

The form ScreenWhen clicking a textinput

Google SignIn SDK is failing by throwing error, A non-recoverable sign in failure occurred -catch error: React Native

$
0
0

I have been trying to integrate Social login in my react native project in which I was able to do facebook login successfully but it is failing to signin to google. react-native-google-signin library is used for google.

The code I have used.

componentDidMount() {GoogleSignin.hasPlayServices({ autoResolve: true }).then(() => {// play services are available. can now configure library}).catch((err) => {console.log("Play services error", err.code, err.message);})GoogleSignin.configure({scopes: ["https://www.googleapis.com/auth/drive.readonly"], // what API you want to access on behalf of the user, default is email and profile// iosClientId: <FROM DEVELOPER CONSOLE>, // only for iOSwebClientId: "xxx", // client ID of type WEB for your server (needed to verify user ID and offline access)// offlineAccess: true // if you want to access Google API on behalf of the user FROM YOUR SERVER//hostedDomain: '' // specifies a hosted domain restriction//forceConsentPrompt: true // [Android] if you want to show the authorization prompt at each login//accountName: '' // [Android] specifies an account name on the device that should be used}).then(() => {// you can now call currentUserAsync()});    _signIn = async () => {        try {            await GoogleSignin.hasPlayServices(              )          const userInfo = await GoogleSignin.signIn();          console.log('User Info --> ', userInfo);          this.setState({ userInfo });        } catch (error) {          console.log('Message', error.message);          if (error.code ===  statusCodes.SIGN_IN_CANCELLED) {            console.log('User Cancelled the Login Flow');          } else if (error.code === statusCodes.IN_PROGRESS) {            console.log('Signing In');          } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {            console.log('Play Services Not Available or Outdated');          } else {            console.log('Some Other Error Happened');          }        }      };

The error response:

Message: A non-recoverable sign in failure occurred -catch error

React Native - Show incoming video call screen in Android (VOIP app)

$
0
0

I am trying to implement video calling feature in react native app. I have used React native twilio video webrtc. I have implemented the same and got it working.

I don't exactly know the flow of Video calling in mobile apps. The flow which I am using for video calling is as follows:

  1. User 1 taps to call User 2
  2. Your app generates a unique name for a Room. Perhaps a combination of the two user's IDs.
  3. User 1 connects to Room with generated unique name
  4. Using FCM, send message of high priority with the unique name of the Room and token to User 2
  5. User 2 to receives notification and you display a ringing UI(even when the app is killed and phone is locked)
  6. User 2 accepts and connects to the same Room

Now I am stuck on point 5.I am sending the FCM notification(which shows up in tray (edit: now using voip notif) to user2 and now I need to show ringing UI on user2's mobile even if the app is killed and phone is locked. How can I achieve this?

I guess there is a package called react-native-callkit, which I should be using along with PushKit for the same. But the problem is with android flow. PushKit and CallKit is not supported in android. So, when app is in killed state the notification appears I need to grab the control and display ringing UI and wake the screen if the phone is locked and app is killed.

Some Confusions

Is there any special type of push notification which doesn't get displayed in the tray? (edit: data messages and VOIP notif I guess)

Is there any other package than react-native-callkit(for displaying ringing UI) which can be used for both android and ios?

React Native - React Navigation Deep Link Does not work on Android

$
0
0

currently i'm working on React Native Android Project, I want to use deep link on some page.But somehow the link always redirect to login page instead of signup page.

already tried adb shell am start -W -a android.intent.action.VIEW -d "myapp://mobile/signup"

i am afraid incorrect in nested navigation.

or should I put path on all screen? because i dont put it all

"react-navigation": "^3.11.1""react-native": "0.60.4"

router.js

const prefix = 'myapp://'<Navigation ref={(comp) => (this.navigator = comp)} uriPrefix={prefix} />

navigation/index.js

const LoginStack = createStackNavigator(    {      LoginScreen: { screen: LoginScreen },      SignUpScreen: {         screen: SignUpScreen,        path: 'signup',       },      ForgotPasswordScreen: { screen: ForgotPasswordScreen },    },    {      navigationOptions: { tabBarVisible: false },    },    {      mode: "modal",      header: null,      transitionConfig: () => TransitionConfig,    });const AppNavigator = createBottomTabNavigator(    {      Default: {        screen: HomeStack,        navigationOptions: {          tabBarIcon: ({ tintColor }) => (<TabBarIcon icon={Images.Icon} tintColor={tintColor} />          ),        },      },      LoginStack: {         screen: LoginStack,        path: 'login',       },    },    {      initialRouteName: 'Default',      tabBarComponent: TabBar,      tabBarPosition: "bottom",      swipeEnabled: false,      animationEnabled: false,      tabBarOptions: {        showIcon: true,        showLabel: true,        activeTintColor: Color.tabbarTint,        inactiveTintColor: Color.tabbarColor,      },      lazy: true,      navigationOptions: {        gestureDirection: I18nManager.isRTL ? "inverted" : "default",      },    });const AuthNavigator = createStackNavigator(  {    LoginScreen: { screen: LoginScreen },    SignUpScreen: {       screen: SignUpScreen,      path: 'signup',     },  },  {    mode: "modal",    header: null,    transitionConfig: () => TransitionConfig,  });export default createAppContainer(  Config.Login.RequiredLogin    ? createSwitchNavigator(        {          AuthLoading: AuthLoadingScreen,          App: AppNavigator,          Auth: AuthNavigator,        },        {          initialRouteName: "AuthLoading",        }      )    : AppNavigator);

AndroidManifest.xml

<activity        android:name=".MainActivity"        android:label="@string/app_name"        android:exported="true"        android:launchMode="singleTask"        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"        android:windowSoftInputMode="adjustResize"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter><intent-filter><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:scheme="myapp" android:host="mobile" /></intent-filter></activity>

any help would be appreciated :)

React Native Android: Could not get BatchedBridge, make sure your bundle is packaged correctly

$
0
0

My app is running fine on Android in debug mode. But in release mode it crashes with this error:

com.facebook.jni.CppException: Could not get BatchedBridge, make sure your bundle is packaged correctly

I have enabled bundle in release:

project.ext.react = [  enableHermes: true,  bundleInRelease: true,]

When I inspect my app bundle I can see index.android.bundle in base/assets folder. It is also in build/intermiates/assets.

I am building my app using fastlane:

lane :internal do  android_set_version_code()  gradle(task: "bundleRelease")  supply(track: 'internal', skip_upload_apk: true)end

How can I fix this?


Not receiving notification when app is close/background on galaxy/samsung emulator/device

$
0
0

I am using microsoft notification hub to send notification on android device. I am using react native azure notification hub npm library. But I am getting inconsistent behaviour in notification. Sometime I get notification, sometime don't on my galaxy/samsung device when app is in foreground. When my app is closed or in background, I am not getting any notification on my galaxy/samsung device. Same behaviour I am getting on galaxy emulator also. One of my friend tested on his emulator Nexus, he was getting notification even when app was closed. Any help how to resolve this intermittent notification on all devices

drawer-navigation doesn't hide screen

$
0
0

I am using react-navigation 5 and I have stack navigation and inside drawer navigation, I want to hide some of the drawer's navigation screens. So, I pass null in drawerLabel attribute as follow

import * as React from 'react';import {createDrawerNavigator} from '@react-navigation/drawer';import ShowNotes from "../screens/notes/ShowNotes";const Drawer = createDrawerNavigator();const DrawerNavigation = () => {    return (<Drawer.Navigator><><Drawer.Screen                     name="Home"                     component={ShowNotes}                    options={{                        headerTitle: 'All Notes',                        drawerLabel: () => null                    }}                /></></Drawer.Navigator>   );}export default DrawerNavigation;

This DrawerNavigation is inside a StackNavigation like so

const Stack = createStackNavigator();const Navigation = ({auth}) => {return (<NavigationContainer theme={CustomTheme}><Stack.Navigator            screenOptions={({navigation}) => ({                headerLeft: () => (<Button                        onPress={() => navigation.dispatch(DrawerActions.openDrawer())}                        title="Info"                        color="#fff"                    />                ),            })}><Stack.Screen                            name="Home"                            component={DrawerNavigation}                        /><Stack.Screen                            name="AddNoteScreen"                            component={AddNote}                        /><Stack.Screen                            name="UpdateNoteScreen"                            component={UpdateNote}                        />            }</Stack.Navigator></NavigationContainer>);};const mapStateToProps = state => {    return {auth: state.auth};};export default connect(mapStateToProps, {})(Navigation);

What I see on my screen is the drawer doesn't contain my screen but an empty blank area which is clickable

enter image description here

How I can stop displaying a screen in drawer?

Cheers

How to get overflow visible working on an image with flex on Android with React Native V0.61 and Expo

$
0
0

I'm using React Native 0.61 with Expo SDK 37 which should support overflow visible as stated in the docs (https://reactnative.dev/docs/image-style-props#overflow). Nevertheless I can't get this to work on Android. I know there were some issues to this topic, but they all seem to be closed and resolved on GitHub (https://github.com/facebook/react-native/issues/6802).So how can I get this to work? Or is there even another way to achieve this picture?

Here is a snap where you can see the different behaviors. It behaves like intended on iOS but it's clipping on Android.

Here you can have a look at the code:https://snack.expo.io/3C9xHTkUp

Issue in pictures:

IOS

Android

npm install for react-navigation-drawer not working

$
0
0

Following is the error on the terminal after running the command.

npm ERR! code ENOENTnpm ERR! syscall renamenpm ERR! path C:\react-native\reviewsApp\node_modules\@react-navigation\drawernpm ERR! dest C:\react-native\reviewsApp\node_modules\@react-navigation\.drawer.DELETEnpm ERR! errno -4058npm ERR! enoent ENOENT: no such file or directory, rename 'C:\react-native\reviewsApp\node_modules\@react-navigation\drawer' -> 'C:\react-native\reviewsApp\node_modules\@react-navigation\.drawer.DELETE'npm ERR! enoent This is related to npm not being able to find a file.npm ERR! enoentnpm ERR! A complete log of this run can be found in:npm ERR!     C:\Users\saumya bhatnagar\AppData\Roaming\npm-cache\_logs\2020-05-28T20_44_21_098Z-debug.log

react-native network error using fetch in android

$
0
0

i am working on my project and when i try to make a request woth fecth sometimes returns me network error im pretty confuse, how i was saying its not always just somtimes if i reload the app works fine and then wrong again.

I already try with http, https, modify the android manifest and nothing works, will apreciate if someone can help.

this is the POST request. it happens also con GET.

fetch(API_URL +'/login/autenticar', {        method: 'POST',        headers: {          Accept: 'application/json','Content-Type': 'application/json',        },        body: JSON.stringify({          tipo: tipo,          email: email,          password: password,        }),      })        .then(response => {          this.setState({            isLoading: false,          });          return response.json();        })        .then(responseJson => {          if (responseJson.flag === false) {            Alert.alert(responseJson.msg);          } else if (responseJson.flag === true) {            AsyncStorage.setItem('userToken', responseJson.data);            this.props.navigation.navigate('Home');          }        })        .catch(error => {          Alert.alert('Please try again'+ error);        });```
Viewing all 28460 articles
Browse latest View live


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