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

Native Base Toast - TypeError: TypeError: TypeError: null is not an object (evaluating 'this.toastInstance._root.getModalState')

$
0
0

I am using react native to build a mobile app. I am facing a Nativ Base Toast issue. When I first load application and then navigate to ticket status, if I go back to a home page with an android back button, following error popup.

Below are my code and error screenshot.

NOTE - This error does not come every time.

Any help would be appreciated.

Thanks in advance

enter image description here

Home.js code (render at application load)

 

    import React, { Component } from 'react';
    import { createDrawerNavigator , tabBarOptions, StackNavigator} from 'react-navigation';
    import Header from './Header';
    import Request from './Request';
    import Navigation from './Navigation';
    import TicketStatus from './TicketStatus/TicketStatus';

    const RootStack = StackNavigator(
        {
            Home: {     screen: Request },
            Navigation: { screen: Navigation },
            TicketStatus: { screen: TicketStatus },
        },
        {
            headerMode: 'none',
            navigationOptions: {
                headerVisible: false,
            }
        }
    );
    RootStack.navigationOptions = {
        header: null
    }
    export default RootStack;

TicketStatus.js code

export default  class TicketStatus extends Component {
    constructor(props){
        super(props)
        this.state = {
            allTickets : [{ name:'Jones Residence', number: '12343534325', classs:'active'},{name:'Rex Bell Elementary', number: '12343534325', classs:'pending' },{name:'CitiBank Offic', number: '123435', classs:'expired' }]
        };
    }
    _fetchTickets(token)
    {
        if(this.mounted) {
            this.setState({
                isloading: true                     
            });
        }
        fetch(config.BASE_URL+'alltickets?api_token='+token,{
            method: 'GET',
            headers: {
                    'Authorization': 'Bearer ' + token,
            }               
        })
        .then((response) => response.json())
        .then((res) => {
            if(this.mounted) {
                if(res.status == 1)
                {
                    this.setState({
                        allTickets: res.data,
                    });                 
                }
                else if(res.status == 0)
                {
                    Toast.show({
                        text: res.message,
                        buttonText: "Okay",
                        duration: 5000,
                        type: "danger"
                    })
                }
                this.setState({
                    isloading: false,
                });
            }
        }).catch(err => {
            if(this.mounted) {
                Toast.show({
                    text: err,
                    buttonText: "Okay",
                    duration: 5000,
                    type: "danger"
                })
            }
        }).done();
    }
    componentDidMount(){
        this.mounted = true;
        this._fetchTickets(config.token);   
    }
    componentWillUnmount(){
        this.mounted = false;
        Toast.hide();
        Toast.toastInstance = null;
    }
    renderTickets = () => {
        return (
            <Content style={{height:300, backgroundColor:"#FFBC42", borderRadius:10}}>
            <ScrollView>
                {
                    this.state.allTickets.map((option, i) => {
                        return (
                            <TouchableOpacity key={i} >
                                <View>
                                    <Text>{option.number} / {option.name}</Text>
                                </View>
                            </TouchableOpacity>
                        )
                    })
                }                   
            </ScrollView>
            </Content>
        )
    }
    render() {
        return (
            <Root>
            <Container>
                <Header {...this.props}/>
                <ScrollView>
                <Content padder>
                    <H1 style={styless.ticket_req}>Check the Status of a Ticket</H1>                                            
                    {this.renderTickets()}  
                </Content>
                </ScrollView>
                {this.state.isloading && (
                        <Loader />
                    )}
            </Container>    
            </Root>
        );
    }
}

React Native - position "absolute" not working in Android

$
0
0

Somehow position: 'absolute' is not working in Android. It's working with iOS, but in Android it's not rendering. Does anybody know how to set position: "absolute" on an Android device?

Button: {
  position: "absolute",
  right: 0,
  top: 0,
  borderRadius: 4,
  borderWidth: 2,
  width: 100,
  height: 40,
  borderColor: 'red',
  backgroundColor: "rgb(72, 120, 166)",
}

How to render data from a buffer? React-Native Javascript

$
0
0

i'm new to react-native and i'm using the library react-native-ble-plx to connect a Heart Sensor to my app and show it's values.

At this point i managed to connect it via bluetooth and store the information on a buffer where i can see with console.log(buffer), as shown in next picture.

enter image description here

My question is how can i render this information to the application? I don't know how to handle it from that buffer.

edit: I specifically want the 2nd value of that buffer (the one that normally is 70)

Here is the code:

scanAndConnect() {
      this.manager.startDeviceScan(null,
                                   null, (error, device) => {
          this.info("Scanning...");

          if (error) {
            this.error(error.message);
            return;
          }
          console.log(device.name)
          //if (device && device.name == 'Inspire HR') {
            if (device && device.name == 'HX-00043494') {
            this.manager.stopDeviceScan()
             device.connect()
               .then((device) => {
                 this.info("Discovering services and characteristics ")
                 return device.discoverAllServicesAndCharacteristics()
           }).then((device) => {
                 this.info("Setting notifications")
            ``return this.Async_setupNotifications(device);
          })
          .then(() => {
            this.info("Listening...")
           return this.setupNotifications(device)

          }, (error) => {
            this.error(error.message)
          })
      }
    })`
  }


async Async_setupNotifications(device) {
 this.manager.characteristic  = device.characteristicsForService("0000180d-0000-1000-8000-00805f9b34fb");
const buf = Buffer.from(characteristic.value, "base64");
console.log(buf);
console.log (buf[1]);


this.manager.characteristic.isNotifying = true;
this.manager.characteristic.isReadable = true;


 if (error) {
   this.error(error.message)
             }
return ;
}

Thanks a lot for the help so far

React native security Android [closed]

$
0
0

I reverse engineered my react native release signed app, I now can see all js code in index bundle which is only obfuscated not encrypted, in assets directory. I don't want my code to be seen. I reverse engineered one of the app in play store which is made up of react-native but I couldn't see the js bundle. So is it possible to make it secure ?If so how?

React Native Error: TypeError: null is not an object _RNGestureHandlerModule.default.Direction

$
0
0

I have tried many ways to fix this error but all attempts have failed.

  • FOR ANDROID NOT IOS.

_RNGestureHandlerModule.default.Direction

I was trying for android. I found bug react-native-gesture-handler buy I don't know how to fix it.

I am following this instruction step by step https://reactnavigation.org/docs/en/getting-started.html

I tried linking the react-native-gesture-handler manual. and also tried unlinked. I made react-native.config.js with code

exports = {
    dependencies: {
      'react-native-gesture-handler': {
        platforms: {
          android: null,
          ios: null,
        },
      },
    },
  };

I am using System:

 OS: Linux 5.3 Arch Linux undefined
    CPU: (12) x64 Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
    Memory: 16.06 GB / 31.21 GB
    Shell: 5.0.11 - /bin/bash
  Binaries:
    Node: 12.13.0 - /usr/bin/node
    Yarn: 1.19.1 - /usr/bin/yarn
    npm: 6.12.1 - /usr/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  npmPackages:
    react: 16.9.0 => 16.9.0 
    react-native: 0.61.4 => 0.61.4 
  npmGlobalPackages:
    react-native-cli: 2.0.1

"react-navigation": "^2.18.2",
"react-navigation-stack": "^1.10.3"
  • FOR ANDROID NOT IOS.

_RNGestureHandlerModule.default.Direction I wrote about the bug react-native-gesture-handler Github

During the development period my react-native app was working fine with expo and after building stooped working [closed]

$
0
0

My app was working fine in the development environment with expo but after i build to android apk login, logout is working fine but on pressing a button which used to change the state render other view like map loading, and make a get request to HTTP. It got hanged and everything stopped working into my mobile phone

How can I generate an apk that can run without server with react-native?

$
0
0

I've built my app, I can run it on my local simulator (and also on my android device within the same network by changing debug server).

However, I want to build an apk that I can send to someone without access to development server and I want them to be able to test application.

I see there is a section Using offline bundle on iOS section of the documentation. But I couldn't figure out how to accomplish same for android. Is this possible? If so, how?

UPDATE: On the answer to this question (react native android failed to load JS bundle) it is said that offline bundle can be downloaded from development server. But when I obtain the bundle from development server the image files can't be loaded.

Native VideoView in ReactNative

$
0
0

I am trying to write a native VideoView and use it in RN. Howerver,I can't change its width and height.I tried "", but it can only changes the image's size. The view is always fullscreen.

Here is my java file.


React Native receive remote push notification only if app is in background

$
0
0

I am using react-native-push-notification in my react-native app to receive the remote push notifications. Everything is working fine I am getting all notifications when the app is either in foreground or background.

But I want the notifications to show only when the app is in the background. If the app is in the foreground it should not show the notification.

Any help will be really appreciated.

My manifest file contains the following code:

<meta-data  android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_launcher" />
  <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name" android:value="YOUR NOTIFICATION CHANNEL NAME"/>
  <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description" android:value="YOUR NOTIFICATION CHANNEL DESCRIPTION"/>
  <!-- Change the resource name to your App's accent color - or any other color you want -->
  <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color" android:resource="@android:color/white"/>

  <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
  <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
    <intent-filter>
      <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
  </receiver>
  <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>
  <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService">
      <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
  </service>

React Native 0.57.x large images low quality

$
0
0

There is really low quality when loading large bundled images, even when using resizeMethod="resize". This happens only on Android, not on any iOS simulator/device. Have tested it on Android 8.1 emulator and LG G6 with Android 8.0. Please see the screenshots bellow.

At the left screenshot we see the exact same code running with RN 0.56.0 and at the right screenshot we see RN 0.57.5. The code is just a simple image <Image source={require('./assets/ELHall1.png')} resizeMethod="resize" /> and the image size is 2111 x 4645 pixels. Both projects are fresh installed using react-native init RN057ImageTest and react-native init --version="0.56.0" RN056ImageTest.

Simple App with an Image

...
type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        {/*<Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>*/}
        <Image source={require('./assets/ELHall1.png')} resizeMethod="resize" />
      </View>
    );
  }
}
...

I have created a Github issue to RN repo since September but noone has replied which makes me think that I am doing something wrong. Is there a new prop or an other way to make large images show normal with full quality in RN 0.57.x? Maybe the metr obuilder updates to 0.57.x have changed how the bundler handles the image assets? I have used resizeMethod prop to "scale" and "resize" with no difference at all. I have used PNG8, PNG24 and PNG32 all same result.

EDIT

The Github repo with the code and the PNG image files: https://github.com/clytras/RN057ImageTest

Please don't give any answers about JPEG images and that they do work, I already know that; I want to make PNG images work like they do in RN 0.56.

react-native-fs.the actual document directory path in android

$
0
0

I tried the code for creating a file, and i created two files, and that is

    // require the module
    var RNFS = require('react-native-fs');

    // create a path you want to write to
    var path = RNFS.DocumentDirectoryPath + '/test.txt';

    // write the file
    RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
    .then((success) => {
    console.log('FILE WRITTEN!');
    })
    .catch((err) => {
    console.log(err.message);
    });

i created two files with that code. but i cant see the actual created files. Where exactly it was saved?

Could not compile settings gradle React Native

$
0
0

The app worked for me from another machine, now that downloading the files from the repository on another computer gives me this problem

FAILURE: Build failed with an exception.

  • Where: Settings file 'C:\Users\samue\Desktop\MCGPS\TeachAll\android\settings.gradle'

  • What went wrong: Could not compile settings file 'C:\Users\samue\Desktop\MCGPS\TeachAll\android\settings.gradle'.

    startup failed: General error during semantic analysis: Unsupported class file major version 57

React Native - Loading percentage on Splash Screen Android & IOS

$
0
0

Is it possible to show progress percentage on splash screen for Android & IOS?

If yes? Then showing progress at splash screen is good practice or not.

Unable to build React-Native project in android studio

$
0
0

After react-native init AwesomeProject command, I'm trying to open the project in android studio. But android studio unable to detect the project.

toLowerCase on TextInput value is creating duplicate text if capital letter created

$
0
0

This one's an interesting one.

I created a TextInput that takes a value, then lower cases it, adds it to state, and sets it as the default value. On my android physical device, if you force a capital letter ( autocapitalize is set to none), and then quickly tap other letters, it will duplicate and add extra text.

Is there a way to avoid this?

Here's a snack https://snack.expo.io/Hk1reKHJ4

Run it on your android or on the simulator, tap the upper case button on the keyboard, tap a few other letters, tap the upper case again, tap a few other letters, and you should set this error.

Thanks!

export default class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      text: ''
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={ styles.inputContainer }
          defaultValue={ this.state.text }
          autoCapitalize="none"
          onChangeText={ value => this.setState({ 
            text: value.trim().toLowerCase()
            })}
        />
      </View>
    );
  }
}

Navigation error with react native latest version 0.61.4

$
0
0
I upgraded my old project in react native version(0.61.4) then getting error related navigation option undefined.

Old project dependency version:-- "react": "16.8.3", "react-native": "0.59.5", "react-navigation": "1.0.0-beta.3", New Project dependency versions:-- "react": "16.9.0", "react-native": "0.61.4", "react-navigation": "^4.0.10", "react-navigation-stack": "^1.10.3", Note:-- I also tried with navigation version 2, 3. please help

code image

error image

React Native on Android: Unable to determine the current character, it is not a string, number, array, or object

$
0
0

I create a new application and insert a old code, when i build the application this error appears:

Script 'C:\Users\nameuser\Desktop\nameapp\node_modules@react-native-community\cli-platform-android\native_modules.gradle' line: 191

What went wrong:

A problem occurred evaluating settings 'nameapp'.

Unable to determine the current character, it is not a string, number, array, or object

The current character read is 'i' with an int value of 105
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
info Run "react-native --help" to see a list of all available commands.

With react-native info command I have the current situation:

info
  React Native Environment Info:
    System:
      OS: Windows 10
      CPU: (8) x64 Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
      Memory: 6.46 GB / 15.85 GB
    Binaries:
      Yarn: 1.15.2 - C:\laragon\bin\nodejs\node-v11\yarn.CMD
      npm: 6.12.0 - C:\Program Files\nodejs\npm.CMD
    IDEs:
      Android Studio: Version  3.5.0.0 AI-191.8026.42.35.5900203

And on the package.json:

{
  "name": "nameapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-community/cli-platform-android": "^2.9.0",
    "axios": "^0.18.0",
    "haversine": "^1.1.0",
    "moment": "^2.22.2",
    "react": "16.6.3",
    "react-native": "^0.59.8",
    "react-native-actionsheet": "^2.4.2",
    "react-native-auto-height-image": "^1.1.0",
    "react-native-cached-image": "^1.4.3",
    "react-native-cli": "^2.0.1",
    "react-native-fbsdk": "^0.8.0",
    "react-native-global-font": "^1.0.2",
    "react-native-google-places": "^3.0.5",
    "react-native-image-crop-picker": "^0.24.1",
    "react-native-image-pan-zoom": "^2.1.10",
    "react-native-image-placeholder": "^1.0.14",
    "react-native-iphone-x-helper": "^1.2.0",
    "react-native-keyboard-manager": "^4.0.13-10",
    "react-native-maps": "github:react-community/react-native-maps",
    "react-native-maps-super-cluster": "^1.4.1",
    "react-native-modal-datetime-picker": "^5.1.0",
    "react-native-open-maps": "^0.3.3",
    "react-native-progress": "^3.4.0",
    "react-native-push-notification": "^3.1.2",
    "react-native-router-flux": "^4.0.6",
    "react-native-share": "^1.2.1",
    "react-native-snap-carousel": "^3.7.4",
    "react-native-swiper": "^1.5.13",
    "react-native-vector-icons": "^4.6.0",
    "react-native-view-shot": "^2.5.0",
    "react-redux": "^5.0.7",
    "redux": "^3.7.2",
    "redux-persist": "^4.10.1",
    "redux-persist-transform-filter": "0.0.15",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.51.1",
    "react-test-renderer": "16.6.3"
  },
  "jest": {
    "preset": "react-native"
  },
  "rnpm": {
    "assets": [
      "./src/fonts"
    ]
  }
}

Thank for the help.

Problem with Handling different screen sizes in Android-React native

$
0
0

I'm a bit confused with handling different size of screens for app.

in android there is a unit named dp that seems to handle screen size and resolution variation. i expect when i use this unit instead of pixels, i see same size component(like button, ...) in every screen. e.g a button with size 20dp must look same size in all screens.

in articles i read that React-Native uses dp as its main unit as well. so expected the same thing here, but it's not working as i expected. a button with 20dp aren't looking the same in different screens.

also there are articles in which they show how to handle different screen sizes, although they say RN using dp they use some arithmetic logic to scale their components to each screen size.

e.g const scaleX = Dimension.getWidth() / baseWdith=> simplified code

the flow is that, we make a UI with an specific base screen and make it look how we want it to be, and then we scale components later in new screens.

my question is that isn't dp unit supposed to do the same thing!? why RN didn't handle autoscaling itself? if there is sth named dp to manage screen sizes-ratio then why they doing manual scaling?

react-native run-android error "Task :app:javaPreCompileDebug FAILED"

$
0
0

EDIT: This issue was solved by forcing the gradle not to jetify my native library. This is done by adding in gradle.properties

android.jetifier.blacklist = your-causing-issues-library

For more details you can read the official docs or this post



I need to use some native code in a react native project. The native code is provided in a .jar file by the hardware manufacturer. In a clean project (react-native init), with this .jar file inside /android/app/libs folder, this error shows as soon as I try to run "react native run-android".

==============

Error is as follow:

Task :app:javaPreCompileDebug FAILED 6 actionable tasks: 6 executed

FAILURE: Build failed with an exception. What went wrong: Execution failed for task ':app:javaPreCompileDebug'. Could not resolve all files for configuration ':app:debugCompileClasspath'. Failed to transform file 'iMagPayV5.1.4.jar' to match attributes {artifactType=android-classes, org.gradle.usage=java-runtime-jars} Execution failed for JetifyTransform: /home/buonapasta/Desktop/React-Native/samples/project/android/app/libs/iMagPayV5.1.4.jar. Failed to transform '/home/buonapasta/Desktop/React-Native/samples/project/android/app/libs/iMagPayV5.1.4.jar' using Jetifier. Reason: 10. (Run with --stacktrace for more details.)

==============

Help is appreciated in advance!! (Sorry if some information is incomplete).

React Native version 0.60.4 running on Ubuntu 18.04. I've tried to include some other .jar files in a clean project without inconvenience, but as soon as I include this particular .jar everything blows. Also, this library is working on an Android Studio project. The .jar can be found on https://github.com/GPaoloni/imagpay-framework

android/app/build.gradle looks like this:

...

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules

    if (enableHermes) {
      def hermesPath = "../../node_modules/hermesvm/android/";
      debugImplementation files(hermesPath + "hermes-debug.aar")
      releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
      implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

android/build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.1")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
    }
}

I just want being able to include the .jar library (to be used by a native activity).

==============

Update:

I've tried doing like sugested:

npm install --save-dev jetifier
npx jetify

But the error still the same.

Reading the npm page of jetifier, in the "Usage for jar/zip/aar files" section:

npm install jetifier
npx jetifier-standalone <your arguments here>

Runing this gives me the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at org.objectweb.asm.ClassReader.readFrameType(ClassReader.java:2313)
    at org.objectweb.asm.ClassReader.readFrame(ClassReader.java:2269)
    at org.objectweb.asm.ClassReader.readCode(ClassReader.java:1448)
    at org.objectweb.asm.ClassReader.readMethod(ClassReader.java:1126)
    at org.objectweb.asm.ClassReader.accept(ClassReader.java:698)
    at org.objectweb.asm.ClassReader.accept(ClassReader.java:500)
    at com.android.tools.build.jetifier.processor.transform.bytecode.ByteCodeTransformer.runTransform(ByteCodeTransformer.kt:39)
    at com.android.tools.build.jetifier.processor.Processor.visit(Processor.kt:443)
    at com.android.tools.build.jetifier.processor.archive.ArchiveFile.accept(ArchiveFile.kt:49)
    at com.android.tools.build.jetifier.processor.Processor.visit(Processor.kt:425)
    at com.android.tools.build.jetifier.processor.archive.Archive.accept(Archive.kt:76)
    at com.android.tools.build.jetifier.processor.Processor.transformLibrary(Processor.kt:421)
    at com.android.tools.build.jetifier.processor.Processor.transform(Processor.kt:247)
    at com.android.tools.build.jetifier.processor.Processor.transform$default(Processor.kt:234)
    at com.android.tools.build.jetifier.standalone.Main.run(Main.kt:157)
    at com.android.tools.build.jetifier.standalone.Main$Companion.main(Main.kt:109)
    at com.android.tools.build.jetifier.standalone.Main.main(Main.kt)

React Native Android / iOS call function on app start

$
0
0

I am new to React Native.

I am trying to call a react native method from native code without having any UI components from RN.

The idea is to add a DeviceEmitter listener at application start and later on post events from Native code.

The question is where should I put JS code to add DeviceEmitter listener at app start?

Viewing all 28479 articles
Browse latest View live


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