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

Negative marginTop not working as intended on Android, works fine in iOS

$
0
0

Example of iOS and Android simulators.

enter image description here

Code:

<View style={styles.test}>
  <Text style={styles.header}>Header Example</Text>
  <Text>Lorem ipsum dolor sit amet</Text>
</View>

Styles:

test: {
  borderWidth: 3,
  borderColor: "#000"
},
header: {
  marginTop: -10,
  backgroundColor: "yellow"
}

Anyone have some insight as to why this happens? Thank you!


Toggle bluetooth for ios device in react-native

$
0
0

Is there a way to toggle bluetooth connectivity for ios in react-native? What I want to achieve is- show nearby bluetooth devices in my app, and if bluetooth is switched off, then switch it on and scan for nearby bluetooth devices. I am using react-native-ble-plx library in my app for this, it is working fine in android, but doesn't seem to work in ios. I am using the below code in android for enabling it-

import { BleManager } from 'react-native-ble-plx';
this.manager = new BleManager();
this.manager.enable();

How can I achieve the above functionality in ios, if it's possible?

My app size of React native app is too large after installation

$
0
0

I ve made a react native app. the release apk size is 28. That is ok, but I was shoked whwn saw the storage size 62 mb. I am despareately searching for solution, please help me, I have to pass my work soon((

Passing Data Using React-Native Navigation

$
0
0

Im trying to pass data between screens in my app. Currently I am using


"react-native": "0.46.0",
"react-navigation": "^1.0.0-beta.11"

I have my index.js


 import React, { Component } from 'react';
    import {
      AppRegistry,
    } from 'react-native';
    import App from './src/App'
    import { StackNavigator } from 'react-navigation';
    import SecondScreen from './src/SecondScreen'    

    class med extends Component {
      static navigationOptions = {
        title: 'Home Screen',
      };

      render(){
        const { navigation } = this.props;

        return (
          <App navigation={ navigation }/>
        );
      }
    }

    const SimpleApp = StackNavigator({
      Home: { screen: med },
      SecondScreen: { screen: SecondScreen, title: 'ss' },    
    });

    AppRegistry.registerComponent('med', () => SimpleApp);

app as

    import React, { Component } from 'react';
    import {
      StyleSheet,
      Text,
      Button,
      View
    } from 'react-native';
    import { StackNavigator } from 'react-navigation';

    const App = (props)  => {
      const { navigate } = props.navigation;

      return (
        <View>
          <Text>
            Welcome to React Native Navigation Sample!
          </Text>
          <Button
              onPress={() => navigate('SecondScreen', { user: 'Lucy' })}
              title="Go to Second Screen"
            />
        </View>
      );
    }

    export default App

then in the secondscreen.js where we will fetch the data which passed from the previous screen as


    import React, { Component } from 'react';
    import {
      StyleSheet,
      Text,
      View,
      Button
    } from 'react-native';

    import { StackNavigator } from 'react-navigation';


    const SecondScreen = (props)  => {
      const { state} = props.navigation;
      console.log("PROPS" + state.params);


      return (
        <View>
          <Text>
            HI
          </Text>

        </View>
      );
    }

    SecondScreen.navigationOptions = {
      title: 'Second Screen Title',
    };

    export default SecondScreen

Whenever I console.log I get undefined.
https://reactnavigation.org/docs/navigators/navigation-prop The docs say every screen should have these values what am I doing wrong?

Accessing Nearby State ; React Native

$
0
0

If I were to have

function a(){
     ...
}

export default class App extends React.Component{
     constructor(props){
          this.state={
               var b: "value"
          }
     }
}

Would there be a way to directly access the state within App out of the nearby non-class function? I'm thinking of something similar to App.setState({}) or anything like that

With function a and class App being written in the same file, but with a just scoped outside of the class.

Styling React Native Picker

$
0
0

I'm attempting to style the text color of the items in a React Native picker. I've only been working in iOS so far, but if I could find a cross-platform solution that'd be awesome.

I've tried the following things:

Styling color on Picker

<Picker style={{color:'white'}} ...etc >

Styling color on Picker Items

<Picker.Item style={{color:'#fff'}} label={'Toronto'} value={'Toronto'} />

I've also seen some examples of adding a color property, so I tried this

<Picker.Item color='white' label={'Toronto'} value={'Toronto'} />

At a total loss here. Thanks for any insight!

EDIT: Here's a solution - use itemStyle prop in the Picker element. I believe this is iOS only.

<Picker itemStyle={{color:'white'}} >
      <Picker.Item color='white' label={'Toronto'} value={'Toronto'} />
      <Picker.Item  label={'Calgary'} value={'Calgary'} />
</Picker>

Socket.IO, React Native and Android 9.0 Pie (API 28): not working

$
0
0

Issue

So I have this issue with Socket.io-client (^2.3.0) running on React Native (0.61.5). I already submitted an issue on GitHub, but I'm hoping someone here can help me out.

So first of all: my code works on iOS, but not on Android.

Steps to reproduce

Environment:

  • React Native 0.61.5
  • React 16.9.0
  • Socket.io-client ^2.3.0
  • Android Studio: Android 9.0 Pie API 28

Front end code (simplified): React Native

import io from 'socket.io-client';

useEffect(() => {
    socket = io('https://127.0.0.1:8001', {
        secure: true,
        transports: ['websocket']
    })
    socket.on('message', () => console.log('message received'))
    // cleanup
    return () => socket.close()
}, [])

Back end code (simplified): NodeJS

const io = require('socket.io')(https)

io.on('connection', socket => {
    console.log('connection established')
    socket.on('disconnect', () => console.log('disconnected'))
})

What I did so far?

I tried a few things before submitting an issue and asking this question here. First of all, I tried adding android:usesCleartextTraffic=true to AndroidManifest.XML. It's suggested here and here. I also tried to downgrade socket.io-client to 2.1.0 and even 2.0.4.

Both steps did not work.

Does anyone have an idea what could be the fix of this problem? I need to use websockets, if there is a workaround (or another library), please let me know!

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

$
0
0

I am experiencing a very weird behaviour in my android emulator when using react-navigation v5 in my react native application, which makes me think is a bug.

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

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

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

// some imports here

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

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

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

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

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


Scanning ISBN using phone camera

$
0
0

I'm creating an app that is able to scan the ISBN of a book and then populate fields based off of that number. My main issue is I'm struggling to find a good API that does that. I'm using react native to build my app. Google has only resulted in finding barcode scanners, which is not what I need.

GPS location fluctuating in react native

$
0
0

I am using GPS location in one of my app in react native. I need to track user location at some intervals. but I am getting different latitude and longitude. I have already set it for high accuracy. But it does not return the accurate location of the user. Also, I found GPS return different locations in IOS and Android. Please help me with how I can get exact location of the user.

React-native-camera shows the message takePicture failed

$
0
0

I'm trying to do a text detector device, and I'm having trouble with react-native-camera. First, I have this error message: Preview is paused - resume it before taking a picture. Then I tryed the method resumePreview before takePictureAsync, and the new error message is takePicture failed.

Am I missing something? Below is my code. I hope anyone can help me. Thank you for advance.

import React, { useState, useRef } from "react";
import { View, Text, Button, StyleSheet } from "react-native";
import RNTextDetector from "react-native-text-detector";
import { RNCamera } from "react-native-camera";

const App = () => {
  const camera = useRef(null);

  const takePhoto = async () => {
    try {
      const options = {
        quality: 0.8,
        base64: true,
        skipProcessing: true
      };
      camera.current.resumePreview();
      const { uri } = await camera.current.takePictureAsync(options);
      console.log(uri);
      const visionResp = await RNTextDetector.detectFromUri(uri);
      console.log("visionResp", visionResp);
    } catch (err) {
      console.warn(err);
    }
  };

  return (
    <View style={styles.screen}>
      <RNCamera
        ref={camera}
        type={RNCamera.Constants.Type.back}
        autoFocus={RNCamera.Constants.AutoFocus.off}
        flashMode={RNCamera.Constants.FlashMode.off}
        androidCameraPermissionOptions={{
          title: "Permission to use camera",
          message: "We need your permission to use your camera",
          buttonPositive: "Ok",
          buttonNegative: "Cancel"
        }}
      />
      <View style={styles.titleContainer}>
        <Text style={styles.title}>Reconhecimento de Texto</Text>
      </View>
      <View style={styles.contentContainer}>
        <Button title="Clique para tirar uma foto" onPress={takePhoto} />
        <Text style={styles.contentText}>Teste</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingVertical: 10,
    backgroundColor: "#000"
  },
  titleContainer: {
    height: "10%",
    padding: 10
  },
  title: {
    color: "#FFF",
    fontFamily: "Verdana",
    fontSize: 20
  },
  contentContainer: {
    flex: 1
  },
  contentText: {
    color: "#FFF",
    fontFamily: "Verdana",
    fontSize: 16
  }
});

export default App;

Expo detached android app deep link getting error "This URL doesn't map to any Activity"

$
0
0

I have a fully-functional expo project and I recently ejected it. It is using ExpoKit 36.0.0.

I'm trying to add deep link to the android app, which I'm using App Links Assistant in the Android Studio to add.

After I added an entry in URL Mapping and tried to check URL Mapping, it shows error "This URL doesn't map to any Activity"(I did put MainActivity in URL Mapping and MainActivity class exists). screenshot

I went on to do the second step "Add logic to handle the intent" and I selected .MainActivity(app), but it shows error "Can't insert code, because there is no onCreate method defined in your activity class."screenshot

Should I just add a onCreate method then? How should I write that method so it doesn't affect running normal expo stuff? Sorry if it's not a smart question but I have absolutely no experience whatsoever with android app development.

How to mark user's current location on map in offline using react-native-maps?

$
0
0

I want to mark the user location using gps and overlay a circle around the dropped pin(i.e the current user location) using react-native-maps. This is working fine in online mode on both android and iOS. But I wanted to function this in the same way on offline mode too. I'm using react-native-geolocation-service to fetch the user's current location. Is there any way to implement this functionality in offline mode

how to pass data from java activity to react native

$
0
0

I am unable to pass data from java activity to react native. I am processing a card payment, and when the payment is done, the response is stored in a variable called message. I need to pass this message to my react native code.

// Java module, the data I want to pass is in "message"

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
    /*
     *  We advise you to do a further verification of transaction's details on your server to be
     *  sure everything checks out before providing service or goods.
    */
    if (requestCode == RaveConstants.RAVE_REQUEST_CODE && data != null) {
        String message = data.getStringExtra("response"); // this is the data
        Log.d("RAVE",message);
        if (resultCode == RavePayActivity.RESULT_SUCCESS) {
            Toast.makeText(activity, "SUCCESS " + message, Toast.LENGTH_SHORT).show();
        }
        else if (resultCode == RavePayActivity.RESULT_ERROR) {
            Toast.makeText(activity, "ERROR " + message, Toast.LENGTH_SHORT).show();
        }
        else if (resultCode == RavePayActivity.RESULT_CANCELLED) {
            Toast.makeText(activity, "CANCELLED " + message, Toast.LENGTH_SHORT).show();
        }
    }

}

// @ReactMethod

 @ReactMethod
    public void sayHi(Callback errorCallback, Callback successCallback) {
        try{
            int amount = 30;//call.argument("amount");
                        String narration = "Payment for soup";//call.argument("nara");
                        String countryCode = "NG"; //call.argument("countryCode");
                        String currency =  "NGN"; //call.argument("currency");
                        String amountText = "50";//call.argument("amountText");
                        String email = "hjjjkdf.com";//call.argument("email");
                        String name = "Danny";//call.argument("name");
                        String paymentId = "a98sjkhdjdu";//call.argument("paymentId");



                        String key ="*****";
                         String encryptionKey = "****";

                                new RavePayManager(activity).setAmount(Double.parseDouble(String.valueOf(amount)))
                                .setCountry(countryCode)
                                .setCurrency(currency)
                                .setEmail(email)
                                .setfName(name)
                                .setlName("")
                                .setNarration(narration)
                                .setPublicKey(key)
                                .setEncryptionKey(encryptionKey)
                                .setTxRef(paymentId)
                                .acceptMpesaPayments(false)
                                .acceptAccountPayments(true)
                                .acceptCardPayments(true)
                                .acceptGHMobileMoneyPayments(false)
                                .allowSaveCardFeature(true)
                                .onStagingEnv(false)
                                .initialize();
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }                  

    }

// React native code

   // async function to call the Java native method
    async sayHiFromJava() {
      HelloWorld.sayHi( (err) => {console.log(err)}, (msg) => {console.log(msg)} );
    }

Please help.

How can I move from splash screen to login screen after some seconds in react native?

$
0
0

I am a beginner in react native and very confused about navigation between two screens after x second delay.


Why am I getting React Native [TypeError: undefined is not an object (evaluating '_this2.setState') error in when changing this.state after biding

$
0
0

I'm a little new to react and I cannot figure out why I get the [TypeError: undefined is not an object (evaluating '_this2.setState')] error when calling

.then(r => {this.setState({ photos: r.edges },() =>
console.log("state after _getPhotosFromDevice: " + JSON.stringify(this.state))

Even after binding the method in the constructor

this._requestCameraPermission = this._requestCameraPermission.bind(this)

I know it has something to do with the 'this' context not being available to it but I can't figure out why. Does it have something to do with the way JS handles async classes? I'm out of ideas here.

Full code

'use strict';

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableOpacity,
  Button
} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import CameraRoll from '@react-native-community/cameraroll';
import Moment from 'moment';

import PermissionsAndroid, {
  NotificationsResponse,
  Permission,
  PERMISSIONS,
  PermissionStatus,
  RESULTS,
} from 'react-native-permissions';

export default class TaskForm extends Component<Props> {

constructor(props) {
    super(props);
    this._requestCameraPermission = this._requestCameraPermission.bind(this)
    this._getPhotosFromDevice = this._getPhotosFromDevice.bind(this)
    this._requestCameraPermission = this._requestCameraPermission.bind(this)
    this.state = {
        task: '',
        type: '',
        stuff: '',
        status: '',
        dueDate: new Moment().format('MM/DD/YYYY'),
        subject: '',
        showDatePicker: false
    };
  }

 submit = (form) => {
      alert( 'task: ' + form.task)

        console.log("form.due date" + JSON.stringify(form.dueDate))

     var newItem = {
         id : Math.floor(Math.random() * 1000000),
         task : form.task,
         status : form.status,
         type : form.type,
         dueDate : form.dueDate,
         stuff : form.stuff,
         subject : [form.subject]
    };

      this.props.navigation.state.params.onGoBack(newItem);
      this.props.navigation.goBack();

   }


    _addPictureToState(r){

        this.state.setState({ photos: r.edges })

    }

    _getPhotosFromDevice = () =>{
            this._requestCameraPermission()
                .then(function (didGetPermission: boolean) {
                console.log("reqCamera ret : " + didGetPermission)
                if (didGetPermission) {

                     CameraRoll.getPhotos({
                        first: 20,
                        assetType: 'Photos'
                      })
                      .then(r => {this.setState({ photos: r.edges },() =>

                                console.log("state after _getPhotosFromDevice: " + JSON.stringify(this.state))

                            )
                      })
                      .catch((err) => {
                        console.info(err);
                      })

                }else{
                     alert("Oh no no permissions!")
                }
            });

    }

    async _requestCameraPermission(){

        console.log("entering _requestCameraPermission")
        var perm = await PermissionsAndroid.request(PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE,{

        title: 'Hey you need to give us contacts permissions!',
         message: 'We need to read your contacts so we can sell them to advertisers.'
        });
        console.log("requesting permission : " + perm);
        return perm === RESULTS.GRANTED;

    }

 render(){
    var date = this.state.dueDate
    return(
       <View style = {styles.container}><TextInput
             style = {styles.input}
             placeholder="Task Number!"
             onChangeText={(task) => this.setState({task})}
             value={this.state.text}
           /><TextInput
             style = {styles.input}
             placeholder="Type!"
             onChangeText={(type) => this.setState({type})}
             value={this.state.text}
           /><TextInput
             style = {styles.input}
             placeholder="Stuff!"
             onChangeText={(stuff) => this.setState({stuff})}
             value={this.state.text}
           /><TextInput
             style = {styles.input}
             placeholder="Subject!"
             onChangeText={(subject) => this.setState({subject})}
             value={this.state.text}
           /><TextInput
                style = {styles.input}
                placeholder="Status!"
                onChangeText={(status) => this.setState({status})}
                value={this.state.text}
              /><TouchableOpacity
             style = {styles.input}
             onPress={() => {
                this.setState({showDatePicker: true})
                console.log("in text area: " + JSON.stringify(this.state));
              }}><Text style = {styles.input} >{this.state.dueDate.toString()}</Text></TouchableOpacity><View>
               { this.state.showDatePicker &&(<DateTimePicker
                    value={new Date()}
                    mode='date'
                    display='default'
                    onChange={ (event, selectedDate)  => {
                        this.setState({showDatePicker: false, dueDate:Moment(selectedDate).format('MM/DD/YYYY')},()=>console.log("afterOnChange: " + JSON.stringify(this.state)))
                     }} />
                )}</View><Button
                 title='View Photos'
                 onPress={ () => this._getPhotosFromDevice()}
               /><TouchableOpacity
              style = {styles.submitButton}
              onPress = {
                 () => this.submit(this.state)
              }><Text style = {styles.submitButtonText}> Submit </Text></TouchableOpacity></View>
    )
 }

}

const styles = StyleSheet.create({
   container: {
      paddingTop: 23
   },
   input: {
      margin: 1,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 40,
   },
   submitButtonText:{
      color: 'white'
   }
})

Which version does React Native support (iOS and Android)?

$
0
0

I can't find this information. Is it true that Android React Native runs on sdkMin18 and therefore makes it supported by most android versions?

react-native android: Debug mode is broken

$
0
0

I think my debug mode for android is kinda broken. I cannot open the debug menu, event though I have yellow-orange boxes for warnings on my device (which tells that i'm running the app on debug mode). No chrome tab opens with a debugger when i run a react-native run-android.

The metro bundler doesn't seem to bundle anything by the way. I used to have a green progress bar but now nothing, even though my app does start on my device.

metro bundler

react-native log-android gives me logs from the app, as if I was looking a the console.

adb shell input keyevent 82 doesn't do anything.

React Native version:

System:
      OS: Windows 10
      CPU: (12) x64 Intel(R) Core(TM) i7-8750H CPU 
@ 2.20GHz
      Memory: 6.96 GB / 19.74 GB
    Binaries:
      Yarn: 1.17.3 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
      npm: 6.4.1 - C:\Program Files\nodejs\npm.CMD 
    IDEs:
      Android Studio: Version  3.5.0.0 AI-191.8026.42.35.6010548


"react": "16.8.3",
"react-native": "0.59.9",

I wasn't able to find anything online on this issue. I don't know what caused that, I've just joined the project and the repository is a mess...

Did you guys had this issue before ?

React navigation adding "more" tab with a pop up list and not navigate to tab

$
0
0

I am basically trying to add a "more" button for both iOS and ANDROID, which pops up a list of options to choose from. Something that looks like this (IOS more button) and (ANDROID more button).

I am using React Navigation to create the TabNavigator TabBar and I know how to add a new tab, I'm just not sure how to create a small menu list thats generated when i click on the tab button instead of navigating me to the tab button screen.

Any ideas on how to go about that?

React-Native TypeORM: Cyclic dependency "t" Android Release build

$
0
0

I am using TypeORM in a React-Native app in which I need SQLite storage. It works really well, except for a bug that I've been struggling with all week.

My scheme contains several objects that are related to one another with one-to-may, many-to-one, and many-to-many relations. Sometimes, one entity has multiple many-to-many relations.

I am developing this app mainly on Android, and in debug mode it works perfect. Saving and reading data goes smooth, It does exactly what I expect. In release mode, however, I keep on getting a very cryptic error message:

[Error: Cyclic dependency: "t"]

TypeORM usually does a good job in telling you what's wrong. Here, however, it gives me no info whatsoever about where I made a mistake, on what entity. Also, googling this error message, or looking it up on their website, gives me no result.

Question: I have been struggling with this all week without any results. Can anyone tell me:

  • What does this message mean?
  • Is this something I did wrong in my code, or a bug in TypeORM?
  • If I'm causing this: How did I, and how can I solve it?
  • Why does it only appear in android release mode, and does it work completely fine in Android debug mode?

Any help would be highly appreciated.

Viewing all 29525 articles
Browse latest View live


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