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

Fetch request displaying response on iOS but not working with android

$
0
0

I am trying to send a response from a fetch request using React-Native for client-side and Node/Express for the server. Unfortunately, the value is only displayed with iOS emulator and not with android. I came across an article in github https://github.com/facebook/react-native/issues/24627 suggesting to add some code on the AndroidManifest file but it is still not working, I tried devices from API 25 to 29 and it worked with none. Can someone please help? Thanks for your time.

Frontend

import React, { Component } from "react";
import {Modal, StyleSheet, View, StatusBar, Text} from 'react-native'
import { Provider } from 'mobx-react';
import StateStorage from './StateStorage';


export default class App extends React.Component {

  constructor (props) {
    super(props)
    this.state ={

      data:''

    }
  }
  componentDidMount(){
    this.callBackendAPI()
    .then(res => this.setState({ data: res.express }))
    .catch(err => console.log(err));
  }
  callBackendAPI = async () => {
    const response = await fetch('http://localhost:5000');
    const body = await response.json();

    if (response.status !== 200) {
      throw Error(body.message) 
    }
    return body;
  };
  render() {
    return (
      <Provider store={StateStorage}>

<Text style={{top:100}}>{this.state.data}</Text>
        </Provider >
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',

  },

});

Backend

const express = require('express')
const app = express()
const port = process.env.PORT || 5000;

app.get('/', (req, res) => {
    res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' })
}
)





app.listen(port, () => console.log(`Example app listening on port ${port}!`))

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
  package="com.mapp">

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

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:usesCleartextTraffic="true"
      tools:targetApi="28"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        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>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
       <meta-data
     android:name="com.google.android.geo.API_KEY"
     android:value="AIzaSyD4Js3-PNHs1aL4XEmw6mAomblC2b4ys5s"/>
    </application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

React native Hot reloading not working in android after creating new project

$
0
0

I have one react-native old project with "^0.59.8" and a new project with "0.61.4".

Earlier hot reloading was working fine in the old android app. But when I have started work with a new one, old projects hot reloading is not at all starting. Whereas the new projects hot reloading is working perfectly fine.

Let me know if u have any suggestions or solutions.

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

$
0
0

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

Andoid Nexus 10 API 28 emulator

Amazon Fire Tablet 8th Gen.

iPad Pro (11-inch) simulator

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

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

Fetch data from php url to save to local sqlite in react native

$
0
0

I want to fetch data from url, example from json.php and then store that to local sqlite in React Native. But I can't find any reference or any problem same like me

I tried to find another database to get data from url and store to local database, but it seems I can't find any case like me.

[{
  "username":"****",
  "password":"*****",
  "access":"1",
  "name":"dwi",
  "phone_number":"****",
  "email":"**@***.com",
  "score":null,"status":"0"
 },
 {
  "username":"*****",
  "password":"****",
  "access":"1",
  "name":"******",
  "phone_number":"**********",
  "email":"******@**.com",
  "score":null,
  "status":"0"
 }]

React Native Android App crashing with "E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules"

$
0
0

Crash my app after install and config react-native-maps and @react-native-firebase/app in existing projects.

Environment info

OS: Windows 10
CPU: (4) x64 Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
Memory: 2.08 GB / 11.90 GB
Binaries:
Node: 10.16.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.9.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.9.0 - C:\Program Files\nodejs\npm.CMD
SDKs:
Android SDK:
  API Levels: 23, 25, 26, 27, 28
  Build Tools: 23.0.1, 25.0.1, 25.0.2, 25.0.3, 26.0.1, 26.0.2, 26.0.3, 27.0.3, 28.0.1, 28.0.2, 28.0.3
  System Images: android-23 | Intel x86 Atom_64, android-23 | Google APIs Intel x86 Atom, android-23 | Google APIs Intel x86 Atom_64, android-26 | Google APIs Intel x86 Atom, android-28 | Intel x86 Atom_64, android-28 | Google Play Intel x86 Atom
IDEs:
Android Studio: Version  3.5.0.0 AI-191.8026.42.35.5900203
npmPackages:
react: 16.9.0 => 16.9.0
react-native: 0.61.4 => 0.61.4

Part of my app dependencies:

"@react-native-firebase/app": "^6.0.3",
"react-native-maps": "0.26.1",

Steps To Reproduce

I did a debug through the Aandroid studio and get following error

--------- beginning of crash 11-13 15:00:24.209 4709-4746/com.melk.android E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules Process: com.melk.android, PID: 4709 java.lang.NoClassDefFoundError: com.google.android.gms.maps.GoogleMapOptions at com.airbnb.android.react.maps.AirMapManager.(AirMapManager.java:60) at com.airbnb.android.react.maps.MapsPackage.createViewManagers(MapsPackage.java:40) at com.facebook.react.ReactInstanceManager.getOrCreateViewManagers(ReactInstanceManager.java:782) at com.facebook.react.CoreModulesPackage.createUIManager(CoreModulesPackage.java:184) at com.facebook.react.CoreModulesPackage.getModule(CoreModulesPackage.java:152) at com.facebook.react.TurboReactPackage$ModuleHolderProvider.get(TurboReactPackage.java:122) at com.facebook.react.TurboReactPackage$ModuleHolderProvider.get(TurboReactPackage.java:110) at com.facebook.react.bridge.ModuleHolder.create(ModuleHolder.java:188) at com.facebook.react.bridge.ModuleHolder.getModule(ModuleHolder.java:153) at com.facebook.react.bridge.NativeModuleRegistry.getModule(NativeModuleRegistry.java:148) at com.facebook.react.bridge.CatalystInstanceImpl.getNativeModule(CatalystInstanceImpl.java:479) at com.facebook.react.bridge.CatalystInstanceImpl.getNativeModule(CatalystInstanceImpl.java:466) at com.facebook.react.uimanager.UIManagerHelper.getUIManager(UIManagerHelper.java:31) at com.facebook.react.ReactInstanceManager.attachRootViewToInstance(ReactInstanceManager.java:1054) at com.facebook.react.ReactInstanceManager.setupReactContext(ReactInstanceManager.java:1012) at com.facebook.react.ReactInstanceManager.access$1400(ReactInstanceManager.java:125) at com.facebook.react.ReactInstanceManager$5$2.run(ReactInstanceManager.java:972) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:26) at android.os.Looper.loop(Looper.java:148) at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:225) at java.lang.Thread.run(Thread.java:818)

Reproducible sample code

android/build.gradle

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.2")

        classpath 'com.google.gms:google-services:4.2.0'
    }
}

React native Android know every moment how much connection you are consuming

$
0
0

I would like to realize in react native an app for android that allows me to know every moment how much I'm consuming, how can I know this information in android?

And to know if the connection you are using is data or wifi.

One thing as seen in the image.

enter image description here

Gradle transform cache in React-Native

$
0
0

I'm trying to modify the jar files in node_modules/react-native/android/com/facebook/react/react-native/{RN_VERSION} but my build keeps getting the file from ~/.gradle/caches/transforms-2 instead of using the file I modified.

I cleaned the project and deleted ~/.gradle/caches/ trying to force the files to be generated once more from the "original" files, but they don't change.

How do I find out where these files are generated? Is there a gradle mapping file somewhere?

react-native build error: Could not find method implementation() for arguments [jscFlavor] on project ':app' of type org.gradle.api.Project

$
0
0

I have kept android emulator running.

This is the error I get when I run react-native run-android :

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details. Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

  • Where: Build file '/Users/yashatreya/Desktop/Realyze/Realyze/android/app/build.gradle' line: 209

  • What went wrong:

A problem occurred evaluating project ':app'.

Could not find method implementation() for arguments [org.webkit:android-jsc:+] on project ':app' of type org.gradle.api.Project.

  • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

This is my app/build.gradle:

apply plugin: "com.android.application"
import com.android.build.OutputFile

project.ext.react = [
    entryFile: "index.js",
    enableHermes: false,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false


def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+' // Error seems to be coming from here, as displayed in the error message

def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.realyze"
        minSdkVersion 21 
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    // rootProject.ext.minSdkVersion
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://facebook.github.io/react-native/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    implementation project(':react-native-sound')
    implementation project(':react-native-audio')
    implementation 'com.android.support:multidex:2.0.1'
    // implementation project(':@react-native-community_datetimepicker')
    implementation project(':react-native-gesture-handler')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'
    implementation 'com.google.firebase:firebase-analytics:17.2.0'
    implementation 'com.google.firebase:firebase-auth:19.1.0'
    implementation project(path: ":@react-native-firebase_auth")
    implementation project(path: ":@react-native-firebase_messaging")
    implementation project(path: ":@react-native-firebase_database")
    implementation project(':react-native-datetimepicker')
    implementation project(path: ":@react-native-firebase_firestore")
    implementation project(path: ":@react-native-firebase_functions")
}

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor //error points to this line.
    }
// }

// 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'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'

This is the root build.gradle:

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:3.4.2"
        classpath 'com.google.gms:google-services:4.3.2'

        // 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()
        maven { url 'https://jitpack.io' }
    }
}

I am trying to solve this error since a week now, please help me. Thank you


React Native WebStorm Emulator cannot start - error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`

$
0
0

I'm new to WebStorm and React Native and I encountered an error while setting up my environment that appears unique compared to the other post I've seen.

Objective

I've set up a default project in WebStorm, my goal is to run that project on an Android emulator, I'm using a Windows PC.

What I've tried

I've set up a simple Debug configuration in WebStorm

Picture of my debug configuration

I've also downloaded an Android Emulator thru Android Studio and I have it running on my computer.

Picture of android simulator running beside my WebStorm IDE

Now when I click on run for my debug emulator I get the following error:

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 864 file(s) to forward-jetify. Using 4 workers...
info JS server already running.
'adb' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
infoerror Installing the app... 
Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\Nicol\WebstormProjects\Dog\android\local.properties'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s

Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\Nicol\WebstormProjects\Dog\android\local.properties'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s

    at checkExecSyncError (child_process.js:621:11)
    at execFileSync (child_process.js:639:15)
    at runOnAllDevices (C:\Users\Nicol\WebstormProjects\Dog\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:39)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.

Other Information

Here is a picture of my Path System variables:

a picture of my Path System variables

AWS Pinpoint opts out Android users of pushnotifications by default in react native

$
0
0

I've tried everything to get push notifications for Android to work with Pinpoint in my react native app.

The iOS integration works as expected.

In android, i'm able to record the endpoint, but when I export the endpoint from pinpoint, I can see that the field that controls push notification--OptOut--is set to ALL.

This is the integration that I have in my App.js to record the endpoints:

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

//aws
import Amplify, { Auth } from 'aws-amplify'
import aws_exports from './aws-exports'
import PushNotification from '@aws-amplify/pushnotification'

Analytics.configure(aws_exports);
Amplify.configure(aws_exports)
console.log('exports',aws_exports)
PushNotification.configure(aws_exports);


type Props = {};
class App extends Component<Props> {

  componentDidMount(){

    console.log(PushNotification)
    // get the notification data when notification is received
    PushNotification.onNotification((notification) => {
      // Note that the notification object structure is different from Android and IOS
      console.log('in app notification', notification);

      // required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
      notification.finish(PushNotificationIOS.FetchResult.NoData);
    });
    // get the registration token
    // This will only be triggered when the token is generated or updated.
    PushNotification.onRegister((token) => {
      console.log('in app registration', token);
    });
  }


  render() {
    ...
  }
}

export default codePush(codePushOptions)(App)

Snapping to an interval in react-native with expo

$
0
0

I'm trying to create a scrollView that snaps to points in intervals of 50.

Looking at the ScrollView docs, I should be able to set the snapToInterval prop within my ScrollView element like so, snapToInterval={50}. This works perfectly on iOS but on Android the intervals appear to be slightly larger than what I am setting them to. You can see this as the further down the scrollView you scroll, the "ticks" get further away from their center.

Here is some code to illustrate the issue (snackable):

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

const TickHeight = 50;

export default class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {}
  }

  buildTicks = () => {
    const arr = [];
    for (let i=0; i < 60; i++) {
      arr.push(
        <View style={styles.tick}>
          <Text style={{fontSize: 20}}>{i}</Text>
        </View>
      )
    }
    return arr;
  }

  render() {

    return (
      <View style={styles.container}>
      <View style={styles.header}></View>
      <View style={{flex: 1, justifyContent: "center"}}>
        <View style={{position: "absolute", height: 300, width: "100%"}}>
          <View style={{height: TickHeight, width: "100%", backgroundColor: 'red'}}></View>
        </View>
        <ScrollView 
          style={[styles.redBorder, styles.scroller]} 
          contentContainerStyle={{flexGrow: 1, paddingBottom: TickHeight * 5}}
          snapToInterval={TickHeight}
          scrollEventThrottle={1}
        >
          {this.buildTicks()}
        </ScrollView>
      </View>

        <View style={styles.footer}>
          <Text style={{color: "white"}}>Nav Bar</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: "stretch",
    backgroundColor: '#FAFAFA',
  },
  header: { height: 50, backgroundColor: 'black'},
  scroller: {flex: 1, maxHeight: 300},
  tick: {
    height: TickHeight,
    justifyContent: "center",
    alignItems: "center"
  },
  redBorder: {
    borderColor: 'red',
    borderWidth: 1
  },
  footer: {height: 50, backgroundColor: "black", alignItems: "center", justifyContent: "center"}
}); 

Am I doing something wrong? Is there something else I need to be doing to get this working on Android?

How to draw a curve line in map like facebook traveling post?

$
0
0

Facebook uses open street map in their traveling post type. Anyone please explain how to create this. I want to create a static map image like this:

a sample image of facebook post

package com.geektime.rnonesignalandroid does not exist

$
0
0

I'm trying to setup onesignal for my react native project. I used npm for install. But when i try to run on android emulator via react-native run-android, it gaves this error.

> Task :app:compileDebugJavaWithJavac FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings
53 actionable tasks: 2 executed, 51 up-to-date
/Users/comp/Desktop/MyApp/android/app/src/main/java/com/myapp/MainApplication.java:10: error: package com.geektime.rnonesignalandroid does not exist
import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;
                                      ^
/Users/comp/Desktop/MyApp/android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java:21: error: package com.geektime.rnonesignalandroid does not exist
import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;
                                      ^
/Users/comp/Desktop/MyApp/android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java:61: error: cannot find symbol
      new ReactNativeOneSignalPackage(),
          ^
  symbol:   class ReactNativeOneSignalPackage
  location: class PackageList
3 errors

My MainApplication.java file;

    package com.myapp;

    import android.app.Application;
    import android.util.Log;

    import com.facebook.react.PackageList;
    import com.facebook.hermes.reactexecutor.HermesExecutorFactory;
    import com.facebook.react.bridge.JavaScriptExecutorFactory;
    import com.facebook.react.ReactApplication;
    import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;
    import com.facebook.react.ReactNativeHost;
    import com.facebook.react.ReactPackage;
    import com.facebook.soloader.SoLoader;

At the top of my build.gradle file i added this code block.

buildscript {
    repositories {
        maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal 
    }
    dependencies {
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.1, 0.99.99]'
    }
}

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

I tried to change import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage to import com.geektime.reactnativeonesignal.ReactNativeOneSignalPackage on MainApplication.java but didn't work out.

react-native-ffmpeg: Native module cannot be null (ios) and null is not an object (evaluating 'RNFFmpegModule.enableLogEvents') (android)

$
0
0

I have a basic expo project that I've eject as expokit, and proceeded to run expo install react-native-ffmpeg. When then running expo start I was greeted with Native module cannot be null on my iOS device and null is not an object (evaluating 'RNFFmpegModule.enableLogEvents').

After that, I re-read the react-native-ffmpeg documentation and added pod 'react-native-ffmpeg', :podspec => '../node_modules/react-native-ffmpeg/ios/react-native-ffmpeg.podspec' to my ios/Podfile and ran pod install. Still no luck.

After that, I deleted the node_modules folder and yarn.lock file, re-ran yarn, went into the ios directory, deleted the Pods folder and Podfile.lock file and re-ran pod install and still had no luck!

The error is less than helpful. Any ideas where to look?

React native understand Container and Store

$
0
0

I am working on a react-native app and have few issues understanding some parts of the code. especially the Container and the store concepts.

if anyone can explain to me those concepts and this spinet of code works I would greatly appreciate it.

const CONTAINERS = {}

function addContainer(key, klass, ...args) {
  CONTAINERS[key] = new klass(...args) // eslint-disable-line
  CONTAINERS[key].containers = CONTAINERS
}

addContainer('auth', AuthContainer)
addContainer('activities', ActivitiesContainer)

const CONTAINERS_TO_INJECT = Object.keys(CONTAINERS).map(
  (key) => CONTAINERS[key]
)


export default class App extends Component {

  componentDidMount() {
    this.appState = AppState.currentState
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = nextAppState => {
    if (this.appState.match(/inactive|background/) && nextAppState === 'active') {
      this.nowTime = new Date().getTime()
    } else {
      const openTime = (new Date().getTime()-this.nowTime)/1000

};

  state = {
    isAppReady: false,
    isSplashReady: false,
  }

   _cacheSplashResourcesAsync = async () => {
    const images = [
      require('./assets/images/splash.jpg'),
      require('./assets/images/logo-IH_blue_gold.png'),
    ]

    return cacheImages(images)
  }


  render() {
    if (!this.state.isSplashReady) {
      return (
        <AppLoading
          startAsync={this._cacheSplashResourcesAsync}
          onFinish={() => this.setState({ isSplashReady: true })}
          onError={console.warn}
          autoHideSplash
        />
      );
    }

spinet of React native code and few questions regarding State and Props

$
0
0

I am working on a React Native project that my manager wants me to teak a little bit even though I never worked with react or any web or mobile development. for the most part it's Been fun and I was able to make most of the changes needed, however I am struggling to understand some parts of the code if anyone can make thing a little bit clearer to me. My background is Java.

here I assume handleChange takes an object "updates" than update the state but I am confused of what "changes: {" is and those three dots ...state.changes, ...updates,

handleChange = (updates) => {
    this.setState((state) => ({
      changes: {
        ...state.changes,
        ...updates,
      },
    }))
  }

here I assume mergedUser is unpacking two objects "this.props" and "this.state" to the variables swirly brackets then returning ...userProfile, ...changes, again not sure what's the dots for and also it seems lile userProfile was inside homeStore that was inside screenProps?

get mergedUser() {
    const {screenProps: {homeStore: {userProfile}}} = this.props
    const {changes} = this.state

    return {
      ...userProfile,
      ...changes,
    }
  }

here it looks easy, a set the param TimerId and b try to access TimerId. but why there is "routes[0].routes[0].routes[0]" why not only this.props.navigation.state.TimerId

  a) this.props.navigation.setParams({TimerId})
  b) this.props.navigation.state.routes[0].routes[0].routes[0].TimerId

Lastly this one I have no idea of what's going on on it

export default class LogIn extends Component {
  static propTypes = {
    navigation: PropTypes.object.isRequired,
    screenProps: PropTypes.object.isRequired,
  }
  state = {
    email: '',
  }

My App is not shown on google play on mobile, but on laptop, it's shown

React Native: TouchableOpacity onPress problems inside a ScrollView

$
0
0

I am running react native 0.24.1 and I am experiencing an issue with the <TouchableOpacity> component when it is placed inside an <ScrollView>.

Its onPress events fire fine but there is a special case when they do not. If along with the <TouchableOpacity> component you have a <TextInput>, and the current focus is on the <TextInput> box, then you may click on the <TouchableOpacity> and you will see its onPress event WILL NOT be fired.

At least the first time you do it. Once the focus is NOT on the <TextInput> anymore, you can now press on the <TouchableOpacity> component and its onPress event will fire just fine.

Note that if the <TouchableOpacity> component is placed inside a <View> instead of an <ScrollView> everything works as expected and the above issue does not apply.

Here is some code to demonstrate the problem:

const React = require('react-native');
const {
  Component,
  Dimensions,
  View,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
} = React;


// ----------------------------------------------------------------------------
class TouchableOpacityTest extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {count_onPress:0,count_onPressIn:0,count_onPressOut:0,count_onLongPress:0};
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  onPressEvent(what,e) {
    console.log('what:',what);
    let newState = {};
    newState['count_'+what] = ++this.state['count_'+what];
    this.setState(newState);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  render() {
    let touchableProps = {
      onPress: this.onPressEvent.bind(this,'onPress'),
      onPressIn: this.onPressEvent.bind(this,'onPressIn'),
      onPressOut: this.onPressEvent.bind(this,'onPressOut'),
      onLongPress: this.onPressEvent.bind(this,'onLongPress'),
    }

    return (
      <View style={{flex:1,flexDirection:'column',justifyContent:'flex-start',alignItems:'center',backgroundColor:'blue'}} >
        <ScrollView style={{width:Dimensions.get('window').width*0.9,backgroundColor:'red'}}>
          <TextInput style={{backgroundColor:'rgb(200,200,200)',marginTop:14}}
            placeholder="Focus on me,hide keyboard,and click on text below"
            autoCorrect={false}
          />
          <TouchableOpacity {...touchableProps} >
            <Text style={{fontSize:20,backgroundColor:'pink',marginTop:14}}>
              Click on me!{"\n"}
              onPress:{this.state.count_onPress}{"\n"}
              onPressIn:{this.state.count_onPressIn}{"\n"}
              onPressOut:{this.state.count_onPressOut}{"\n"}
              onLongPress:{this.state.count_onLongPress}{"\n"}
            </Text>
          </TouchableOpacity>
        </ScrollView>
      </View>
    );
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
// ----------------------------------------------------------------------------
AppRegistry.registerComponent('react_native_app1', () => TouchableOpacityTest);

You may replace the <ScrollView> with a <View> component on the above code and you will see that onPress event fires every time, even when the focus is on the <TextView>

NOTE: I am working on Android. I have no idea if this happens also on iOS.

NOTE 2: According to Aakash Sigdel, this is indeed happening on iOS too.

How do you debug React Native?

$
0
0

How does one debug their React code with React Native while the app is running in app simulator?

React native Build failed as "Could not find com.google.android.gms:play-services-ads-identifier:12.0.1"

$
0
0

I am trying to build my react native app with react-native run-android command. But the build is failing with the below error:

FAILURE: Build failed with an exception.

* What went wrong:
Could not resolve all files for configuration ':react-native-onesignal:debugComp                                                                                                                ileClasspath'.
> Could not find com.google.android.gms:play-services-ads-identifier:12.0.1.
  Required by:
      project :react-native-onesignal > com.onesignal:OneSignal:3.12.2

I searched online for a solution and most of the post says to move the google dependency before jcenter() for android/build.gradle file. So, I followed the same as you can see from the code shared below but still the build is failing with the same error. Anyone have faced similar issue?

android/build.gradle file

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

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        // classpath 'com.android.tools.build:gradle:3.1.0'
        classpath 'com.android.tools.build:gradle:3.1.3'
        classpath 'com.google.gms:google-services:3.1.1'

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

allprojects {
    repositories {
        // ADD THIS
        maven { url 'https://maven.google.com' }
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        // ADD THIS
        maven { url "https://jitpack.io" }

        maven {
            // Local Maven repo containing AARs with JSC library built for Android
            url "$rootDir/../node_modules/jsc-android/dist"
        }
    }

    configurations.all {
        resolutionStrategy {
            force 'com.facebook.android:facebook-android-sdk:4.34.0'
        }
    }

    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.google.android.gms'&& !details.requested.name.contains('multidex') ) {
                    details.useVersion "12.0.1"
                }

                if (details.requested.group == 'com.google.firebase') {
                    details.useVersion '12.0.1'
                }
            }
        }
        afterEvaluate {project ->
            if (project.hasProperty("android")) {
                android {
                    compileSdkVersion 27
                    buildToolsVersion "27.0.3"
                }
            }
        }
    }
}
Viewing all 28476 articles
Browse latest View live


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