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

Changing app navigation structure from version 4 to 5 in react native

$
0
0

I was working on an old app using react navigation version 4 the app contains a register and login in page obviously and then the content of the app.

recently I started remaking the content of the app using react navigation version 5 in order to use the shared element animation and the bottom tab navigator and it was fairly simple.

but I struggled with converting the login part to version 5 since the app structure is somewhat complicated and I am somewhat new to react navigation version 5.

i will leave a figure of the app structure bellow a long with samples of the code used.

Navigation used in the app

App.js :

import { setNavigator } from "./app/navigationRef";const articleListFlow = createStackNavigator({  Main: MainScreen, // screen with diffrent articles categories  ResultsShow: ResultShowScreen, // article details screen});const loginFlow = createStackNavigator({  Signup: SignupScreen,  Signin: SigninScreen,});loginFlow.navigationOptions = () => {  return {    headerShown: false,  };};articleListFlow.navigationOptions = {  title: "News Feed",  tabBarIcon: ({ tintColor }) => (<View><Icon style={[{ color: tintColor }]} size={25} name={"ios-cart"} /></View>  ),  activeColor: "#ffffff",  inactiveColor: "#ebaabd",  barStyle: { backgroundColor: "#d13560" },};const switchNavigator = createSwitchNavigator({  ResolveAuth: ResolveAuthScreen,  MainloginFlow: createSwitchNavigator({    //WelcomeScreen: WeclomeScreen,    loginFlow: loginFlow,  }),  mainFlow: createMaterialBottomTabNavigator(    {      articleListFlow: articleListFlow,      ArticleSave: ArticleSaveScreen, // we dont need this one      Account: AccountScreen,    },    {      activeColor: "#ffffff",      inactiveColor: "#bda1f7",      barStyle: { backgroundColor: "#6948f4" },    }  ),});const App = createAppContainer(switchNavigator);export default () => {  return (<AuthProvider><App        ref={(navigator) => {          setNavigator(navigator);        }}      /></AuthProvider>  );};

NavigationRef.js :

import { NavigationActions } from "react-navigation";let navigator;export const setNavigator = (nav) => {  navigator = nav;};export const navigate = (routeName, params) => {  navigator.dispatch(    NavigationActions.navigate({      routeName,      params,    })  );};// routename is the name of the routes singin singup accountscreen// params information we want to pass to the screen we want to show

AuthContext.js

import { AsyncStorage } from "react-native";import createDataContext from "./createDataContext";import userAPI from "../api/user";// using navigate to access the navigator and redirect the userimport { navigate } from "../navigationRef";// AUTHENTICATION REDUCERSconst authReducer = (state, action) => {  switch (action.type) {    case "add_error": {      return {        ...state,        errorMessage: action.payload,      };    }    case "clear_error_message": {      return {        ...state,        errorMessage: "",      };    }    case "signin": {      return {        errorMessage: "",        token: action.payload,      };    }    default:      return state;  }};// CLEARING ERROR MESSAGES WHEN SWITCHING SIGNIN-SIGNUPconst clearErrorMessage = (dispatch) => () => {  dispatch({ type: "clear_error_message" });};// AUTOMATIC SIGNIN ONLY USING TOKENS ON USER DEVICEconst tryLocalSignin = (dispatch) => async () => {  const token = await AsyncStorage.getItem("token");  if (token) {    // if token exists    dispatch({ type: "signin", payload: token });    navigate("Main");  } else {    // if token doesnt exist    navigate("WelcomeScreen");  }};// SIGNUPconst signup = (dispatch) => async ({ email, password }) => {  try {    const response = await userAPI.post("/signup", { email, password });    await AsyncStorage.setItem("token", response.data.token);    dispatch({ type: "signin", payload: response.data.token });    // making use of the navigate component to access navigation    // and redirect the user    navigate("Main");  } catch (err) {    dispatch({      type: "add_error",      payload: "Something went wrong with sign up",    });  }};// SIGNINconst signin = (dispatch) => async ({ email, password }) => {  try {    const response = await userAPI.post("/signin", { email, password });    await AsyncStorage.setItem("token", response.data.token);    // using signin since the logic is the same    dispatch({ type: "signin", payload: response.data.token });    // making use of the navigate component to access navigation    // and redirect the user    navigate("Main");  } catch (err) {    console.log(err);    dispatch({      type: "add_error",      payload: "Something went wrong with sign in",    });  }};// SIGNOUTconst signout = (dispatch) => async () => {  // removing the token makes identification not work again  await AsyncStorage.removeItem("token");  dispatch({ type: "signout" });  navigate("loginFlow");};// CREATING CONTEXT AND PROVIDER OBJECTS FOR AUTHENTICATIONexport const { Provider, Context } = createDataContext(  authReducer,  {    signin,    signup,    signout,    clearErrorMessage,    tryLocalSignin,  },  {    token: null,    errorMessage: "",  });

createDataContext.js

import React, { useReducer } from "react";export default (reducer, actions, defaultValue) => {  const Context = React.createContext();  const Provider = ({ children }) => {    const [state, dispatch] = useReducer(reducer, defaultValue);    const boundActions = {};    for (let action in actions) {      // for every action in the actions, call it with dispatch      boundActions[action] = actions[action](dispatch);    }    return (<Context.Provider value={{ state, ...boundActions }}>        {children}</Context.Provider>    );  };  return { Context, Provider };};

My appologies for the long code and thank you in advance for anyone who can help.


react-native-notification foreground messages

$
0
0

Hi everyone

I use library wix/react-native-notifications

It looks like I do something wrong with my android (ios works fine).For me:

  • registerRemoteNotificationsRegistered
  • registerRemoteNotificationsRegistered
  • registerNotificationOpened
  • getInitialNotification

work good.

But:

  • registerNotificationReceivedForeground
  • registerNotificationReceivedBackground

have never triggered.

I think I put something wrong in AndroidManifest.xml (I have tried different variant but it still doesn't work).

Or problem occurs from using

  • react-native-notification
  • react-native-pusher-push-notifications

at the same time.

Please maybe someone have some ideas?

I use:

  • "react-native-notifications": "^3.2.2",
  • "react-native-pusher-push-notifications": "^2.4.0",
  • "react": "16.9.0",
  • "react-native": "0.61.5",

Part of AndroidManifest.xml that I think can be wrong:

<service  android:name=".java.MyFirebaseMessagingService"  android:exported="false"><intent-filter><action android:name="com.google.firebase.MESSAGING_EVENT"/></intent-filter></service>

How to touch and hold to select text in React Native

$
0
0

I'm new to Android and trying to implement a rich editor using Text component of React Native. However when I touch the text and hold for a moment, the text was not highlighted and the top bar with selection actions was not shown like what behaves in a webview or other applications.What am I missing or do I need to implement this feature by myself? If so could you point a direction?

react-native-webview: distinguish between window.location caused by script and user clicking the link

$
0
0

Is there a way in react-native-webview to distinguish between user-caused and script-caused navigations?

I see that onLoad[Start,End] and onNavigationStateChange events are fired in both cases. Also, if I add logging to WebViewClient.shouldOverrideUrlLoading() or WebViewClient.shouldInterceptRequest(), both fns are invoked if either window.location is changed inside a script, or if user clicks a link. So how can one distinguish these two?

Thanks!

React Native v5, Android 9 - Touch events not triggered

$
0
0

I created a new react native project using expo bare workflow and installed react native v5.

On iOS it is working fine.

But on Android, no touch events are being triggered. Swiping is getting through though.

Any ideas why this might be happening ?

Expo - geofence api not returning values on geofence start

$
0
0

I am attempting to get Expo's geofencing api up and running via a button action in react native.

I've put together an example, but when I attempt to initiate the geofencing action it doesn't do anything. I receive no notification if I am inside or outside a region. Was hoping to get some guidance on this. I can't find a working example. I've already found the following posts that don't seem to work:

Expo startGeofencingAsync not starting

Expo - increase location accuracy with Geofence

App.js

import { StyleSheet, Text, View, Button } from 'react-native';import React, { Component } from 'react';import * as Permissions from 'expo-permissions';import * as Location from 'expo-location';import * as TaskManager from 'expo-task-manager';class App extends Component {state= {  point : {latitude: 0, longitude: 0},  hasLocationPermission: null,  location: null}async componentDidMount() {  this.getLocationsPermissions();  //Permissions.askAsync(Permissions.LOCATION);  //await Location.startLocationUpdatesAsync('firstTask', {  //  accuracy: Location.Accuracy.Balanced,  //});}//update location pointsgetCurrentLoc = async () => {  console.log('retrieving points');  let location = await Location.getCurrentPositionAsync({});  location =  await JSON.stringify(location);  location = await eval( '('+'['+ location +']'+')' );  this.setState({ location: location })}//ask for location permissions getLocationsPermissions = async () => {  let { status } = await Permissions.askAsync(Permissions.LOCATION);  //status && console.log('location: ', status)  if (status !== 'granted') {    this.setState({      errorMessage: 'Permission to access location was denied',    });    } else {      this.setState({ hasLocationPermission : status })    }}_startGeofence = async () => {  console.log('starting geofencing test ...')  Location.startGeofencingAsync('geofence',    [    {      latitude: 40.763882,      longitude: -73.929893,      radius: 50     }     ]    );};  render() {    return (<View><Text>geofence test</Text><Button           onPress={this._startGeofence}          title="AM-I-IN-THE-REGION?"        /><Text>{this.state.location ? `my current location is lat: ${this.state.location[0].coords.latitude}` : `none`}</Text></View>    );  }}export default App;TaskManager.defineTask("geofence", ({ data: { eventType, region }, error }) => {  if (error) {    // check `error.message` for more details.    return;  }  if (eventType === Location.GeofencingEventType.Enter) {    console.log("You've entered region:", region);  } else if (eventType === Location.GeofencingEventType.Exit) {    console.log("You've left region:", region);  }});

What's a good way to store a lot of small texts with metadata with reactNative?

$
0
0

I am developing an app that will displays a series of small texts everyday and I have been wondering what's the best way to store them. I intend to change them only when I update it to new versions so.

Including existing android app+library project as a dependency in anoher project

$
0
0

I have react-native android project where I am trying to include this project in

I have downloaded the repo and put it in my ./react-native-app/android folder.

So far the engine project from 3d-model-viewer imports properly when I have:

./react-native-app/android/settings.gradle

include ':engine'project(':engine').projectDir = new File(rootProject.projectDir, './android-3D-model-viewer/engine');

./react-native-app/android/app/build.grade

dependencies {   //...   implementation project(":engine")   //...}

But the same pattern does not work for the app module inside 3d-model-viewer which contains a bunch of views and other useful classes. I'm assuming this is because it is set up to be a standalone app, and also because it has the same name as my project :app. How do I get it recognized as a library like engine and deal with the conflicting names?


Failed to resolve: com.google.android.gms:play-services-basement:12.0.1

$
0
0

Here is my dependencies

dependencies {        compile project(':react-native-fcm')        // compile 'com.google.firebase:firebase-core:11.2.0' //FCM - this decides your firebase SDK version        compile(project(':react-native-maps')){            exclude group: 'com.google.android.gms', module: 'play-services-base'            exclude group: 'com.google.android.gms', module: 'play-services-maps'        }        compile(project(":react-native-google-place-picker")){            exclude group: "com.google.android.gms"        }        compile (project(':RNAdMob')){            exclude group: "com.google.android.gms"        }        //compile project(':react-native-device-info')        compile project(':react-native-fbsdk')        compile (project(':react-native-mauron85-background-geolocation')){            exclude group: "com.google.android.gms"        }        compile project(':react-native-android-location-enabler')        compile project(':react-native-wheel-picker')        compile project(':react-native-sound')        compile project(':react-native-vector-icons')        compile (project(':react-native-google-analytics-bridge')){            exclude group: "com.google.android.gms"        }        //compile project(':react-native-device-info')        compile(project(":react-native-device-info")){            exclude group: "com.google.android.gms"        }        compile fileTree(dir: "libs", include: ["*.jar"])        compile "com.android.support:appcompat-v7:23.0.1"        //compile "com.facebook.react:react-native:+"  // From node_modules        compile "com.facebook.react:react-native:0.44.3"        compile(project(":react-native-google-signin")){            exclude group: "com.google.android.gms"        }        compile (project(':tipsi-stripe')){            exclude group: "com.google.firebase"            exclude group: "com.android.support"            exclude group: "com.google.android.gms"        }        compile 'com.google.android.gms:play-services-auth:11.0.2' // should be at least 9.0.0        compile 'com.google.android.gms:play-services-places:11.0.2'        compile 'com.google.android.gms:play-services-maps:11.0.2'        //compile 'com.google.android.gms:play-services-location:11.0.2'        compile 'com.google.android.gms:play-services-wallet:11.0.2'        compile 'com.google.android.gms:play-services-gcm:11.0.2'        compile 'com.google.android.gms:play-services-analytics:11.0.2'        compile 'com.google.android.gms:play-services-ads:11.0.2'    }

Error getting from RNAdMob project. but i have excluded the gms package. I didnt do any changes in the code. Yesterday its worked and compiled. I`m wonder why today its not compiling. Im not added "play-services-basement:12.0.1" module anywhere.

How to upload image or document in react native using fetch method with php backend

$
0
0

i am trying to upload an image from Android using react-native, for the upload process i tried to use fetch method to upload the selected image but i am getting this error Network request failed, here's my code

const formData = new FormData();const file = {    name:'file.jpg',    type:'image/jpeg',    uri:'file:///data/user/0/package_name/cache/react-native-image-crop-picker/filename.jpg'};formData.append('photo', file);const uploadUrl = 'http://10.0.2.2/test/upload.php';fetch(uploadUrl,{    method:'PUT',    headers:{'Content-Type':'multipart/form-data',    },    body:formData}).then(res => res.json()).then(res => {    console.log(res)}).catch(err => console.log(err))

my php backend 'upload.php'

<?php$result = false;$err = '';try{    if(isset($_FILES['photo'])){        $file = $_FILES['photo'];        move_uploaded_file($file['tmp_name'],'uploads/'.$file['name']);             $result = true;    }else{        $error = 'field name not found';    }}catch(Exception $e){    $error = $e->getMessage();}$response = array('result' => $result, 'err' => $error);echo json_encode($response);

expected result

{result: true}

Program type already present: androidx.versionedparcelable.NonParcelField

$
0
0

i am working on a react native android project but i am stuck on this error

> Task :app:transformDexArchiveWithExternalLibsDexMergerForDebug FAILEDD8: Program type already present: androidx.versionedparcelable.NonParcelField    FAILURE: Build failed with an exception.

i have tried to change multi dex to false in build.gradle

  defaultconfig {...    multiDexEnabled false      ...}

i dont want to migrate to androidx , i just want to get rid of androidx & this error ;please help me , thanks in advance

DeepLinking React Native App with firebase deeplink

$
0
0

i'm trying to implement deeplink functionality in react native app using firebase deeplink, functionality is similar like sharing functionality of flipkart and amazon app, when we share a product to social media it should redirect to product specific page

i have implemented npm i react-native-share for sharing link with some description and images

code snippet for sharing

       url: "https://stepout.page.link/activity_id/?id="+ this.state.activityType_id,       title: this.state.activityTypeName,       message: "Test Data",       subject: "Share Link", //  for email       social: Share.Social.FACEBOOK})              .then(result => console.log("Share Insta=>", result))              .catch(errorMsg => console.log("Error Share Insta=>", errorMsg))}}

after sharing link to insta when i user clicks on it it will give popup which displays browser and myApp

when i clicked on myApp then i'm getting null

Linking.addEventListener('url', this.handleOpenURL);         Linking.getInitialURL().then((url) => {             console.log('initial url:'+ url)         })

but when i tried with branch i'm getting some value only issue is i have to click on app only, if i'm comming from browser it shows www.google.com

branch.subscribe(({ error, params }) => {            if (error) {                console.error('Error from Branch: '+ error)                return            }kindly help how to handle dynamic link when its clicked from other app, And guide me is there any issue while generating dynamic link            console.log("Params-->", params);        })

React native android( webview does not support JavaScript

$
0
0

I am actually trying to build an apk for my Vuejs(frontend) website using React-native-webview(expo) , and it is working super cool in my phone(andorid 10) , but when i tried to use the app in android6 it is not executing the JavaScript(VueJs) and showing white blank screen. After some research i found that the old verstion of Android webview does not able to execute JavaScript .. https://github.com/facebook/react-native/issues/14754 referring to the site,

So is there any way we can display JavaScript in the android6 phone like the phone browsers are working ?

Expo Permissions work in testing but not in production

$
0
0

In my react native app which I ave published on the Google Play Store, I require Camera Roll permissions. This works during testing, but not in the published version of the app.

  getPermissionAsync = async () => {    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);    if (status !== "granted") {      alert("Sorry, we need camera roll permissions to make this work!");    }    await this.setState({ permission: status === "granted" });  };  _pickMedia = async () => {    if (this.state.permission != true) {      await this.getPermissionAsync();    }    if (this.state.permission == true) {        // get image    }  };

In testing this works as expected, asking permission to access the camera roll every time the user tries to upload a picture till its given. However in production, the user is prompted once for permission to use the camera roll and whether or not they allow it, the alert box comes up and the user is unable to pick an image. If they try to add media again, they aren't prompted for permissions and it just alerts again.

As per the expo docs I have added READ_EXTERNAL_STORAGE to my permissions in app.json:

"android": {"permissions": ["READ_EXTERNAL_STORAGE"],    }

Could someone tell me why this doesn't work in production?

Jw Player Casting not working on auto change next video

$
0
0

i used jw-video in my react native app there is also an implementation of playlist videos now i am adding chromecast feature and iam using jw-cast for that now the issue is when i start casting and video is completed and next video need to play automatically but its not playing instead of that video stuck (without enable casting it's working properly)

  1. React-native: 0.59.10
  2. jw player : 3.4.0
  3. jw cast : 3.4.0

any one had this type of error? so give some idea whats the issue.


Can't find variable: setImmediate (Error)

$
0
0

Seeing the Can't find variable: setImmediate on my emulator when attempting to react-native run-android after the BUILD SUCCESSFUL in 38s and my emulator loads up the app.

I do not use setImmediate anywhere and the error message only appears on the emulator not in my console windows. It does not show where exactly the error appears.

my cli shows

info Reloading app...[Sat May 30 2020 14:36:08.579]  BUNDLE  ./index.js

I have tried the following to resolve this

  • by removing node_modules and reinstalling via npm install
  • deleteing android\app\src\main\res\raw
  • executing cd android && ./gradlew clean && ./gradlew :app:bundleRelease
  • executing cd android && ./gradlew clean && ./gradlew :app:bundleDebug
  • deleting android/app/build
  • building in android studio (it does not show any problems in android studio)

My external imports are:

import { openDatabase } from 'react-native-sqlite-storage';import React from 'react';import { StyleSheet, Text, View, TouchableOpacity, FlatList } from 'react-native';

once again. I do not have setImmediate anywhere in my code.

Using React:

react-native-cli: 2.0.1react-native: 0.62.2

Can't find variable: setImmediate (Error)

Jw Player chromecast not working on auto change next video

$
0
0

i used jw-video in my react native app there is also an implementation of playlist videos now i am adding chromecast feature and iam using jw-cast for that now the issue is when i start casting and video is completed and next video need to play automatically but its not playing instead of that video stuck (without enable casting it's working properly)

  1. React-native: 0.59.10
  2. jw player : 3.4.0
  3. jw cast : 3.4.0

any one had this type of error? so give some idea whats the issue.

react native vector icons not working after export on expo

$
0
0

I use

react-native-vector-icons

and when I run app on emulator everything is ok but after the export with

expo build:android -t apk

and install on real phone all icons got hidden and not showing

Undefined return value using useState and firebase for objects in React Native

$
0
0

I'm writing an app using React Native and I came across an issue when trying to update an Object with the useState method. Here's my code:

const Screen = ({route}) => {    var roomKey = route.params;    const [room, setRoom] = useState({});    db.ref('rooms').on('value', (data) => {        setRoom(() => (data.val())[roomKey]);    });    console.log(room);// rest of the code ...

My code works as follows: first it takes a key outputted by another screen with react navigation, and then calls the firebase database with the ref method (db is defined as Firebase.initializeApp(config).database(), where config is the object with all the firebase datas needed). If I log out the data.val())[roomKey] it correctly outputs the object I'm downloading from database, however the room object is not updated by the useState method (it outputs undefined, making the following part of the code crash). What am I doing wrong?

Setting id's to scheduled notifications

$
0
0

I'm using https://github.com/zo0r/react-native-push-notification to manage the scheduled notifications along with datetimepicker, The thing i have problems with is that i don't know how i can make the cancelNotification work with the id. For example i have 3 scheduled notification ongoing at the same time but then decide i want to cancel the 2nd scheduled notifcation and by pressing the cancelNotification it should only cancel the 2nd and not the latest schedule notification like its doing now. Every scheduled notification has its own cancel button.

Code from the docs

 PushNotification.localNotificationSchedule({  id: 0, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID  //... You can use all the options from localNotifications  message: "My Notification Message", // (required)  date: new Date(Date.now() + 60 * 1000), // in 60 secs}); 

cancelNotification

PushNotification.cancelLocalNotifications({id: '123'});

My own code

import React, { useState } from 'react';import { Text, View, Alert, TouchableWithoutFeedback } from 'react-native';import PushNotification from 'react-native-push-notification';import DateTimePickerModal from 'react-native-modal-datetime-picker';import Entypo from 'react-native-vector-icons/Entypo';import Fontisto from 'react-native-vector-icons/Fontisto';import Feather from 'react-native-vector-icons/Feather';export default function ListItem({ item, pressHandler }) {  const [isDatePickerVisible, setDatePickerVisibility] = useState(false);  const showDatePicker = () => {    setDatePickerVisibility(true);  };  const hideDatePicker = () => {    setDatePickerVisibility(false);  };  const NotifSchedule = date => {    PushNotification.localNotificationSchedule({      id: 0,      priority: 'high',      message: item.text,      date,    });  };  const CancelNotif = () => {    PushNotification.cancelLocalNotifications({      id: '',    });  };  const createTwoButtonAlert = () =>    Alert.alert('Delete this task?','',      [        {          text: 'Cancel',          onPress: () => console.log('Cancel Pressed'),          style: 'cancel',        },        { text: 'Delete', onPress: () => pressHandler(item.key) },      ],      { cancelable: false },    );  return (<TouchableWithoutFeedback><View        style={{          flex: 1,          backgroundColor: '#fff',          padding: 20,          borderRadius: 10,          shadowColor: '#888888',          shadowOffset: { width: 0, height: 1 },          shadowOpacity: 0.8,          shadowRadius: 10,          elevation: 5,        }}><View          style={{            flexDirection: 'row',            borderBottomWidth: 1,            borderBottomColor: '#000',          }}><Fontisto            name="clock"            size={20}            color="#000"            onPress={showDatePicker}          /><Feather            style={{ marginLeft: 10 }}            name="bell-off"            size={20}            color="red"            onPress={CancelNotif}          /><View            style={{              flex: 1,              justifyContent: 'flex-end',              flexDirection: 'row',            }}><Entypo              name="cross"              size={25}              color="#000"              onPress={createTwoButtonAlert}            /></View><DateTimePickerModal            isVisible={isDatePickerVisible}            mode="time"            onConfirm={NotifSchedule}            onCancel={hideDatePicker}            date={new Date()}          /></View><Text style={{ paddingTop: 10 }}>{item.text}</Text></View></TouchableWithoutFeedback>  );}
Viewing all 28463 articles
Browse latest View live


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