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

How to create a pod/aar using react native npm package

$
0
0

I have already created an SDK using react native which has some component & APIs which client can use for different purposes. I want to create SDK's pod & AAR file as well using that react-native package for clients developing in native languages(Swift/JAVA) and don't want to use the react-native package.

Please help me out.


"Unable to load script from assets 'index.android.bundle'. Make sure..."

$
0
0

Seems Metro Bundler is not loading... it is opening and closing and I can see nothing is running inside before closing. For this reason emulator is not running the app.

I am getting the error after running:

react-native init project

react-native run-android

**System:**
    OS: Windows 10
    CPU: (2) x64 AMD A4-6300 APU with Radeon(tm) HD Graphics
    Memory: 1.49 GB / 7.21 GB
  Binaries:
    Node: 12.13.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.19.1 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.12.0 - C:\Program Files\nodejs\npm.CMD
  SDKs:
    Android SDK:
      API Levels: 23, 27, 28
      Build Tools: 23.0.1, 27.0.3, 28.0.3
  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.3 => 0.61.3

package.json

{
  "name": "first_app",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.3"
  },
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/runtime": "^7.6.3",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.6.0",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.3",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

Genymotion Emulator S8 Galaxy

Can't get setBackgroundMessageHandler to work

$
0
0

In react-native-firebase v6, I can't get setBackgroundMessageHandler to work in my app. Notifications are received just fine but the handler is not executed.

I have done it like in the guide to no avail.

import { AppRegistry } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import AsyncStorage from '@react-native-community/async-storage';
import App from './App';
import { name as appName } from './app.json';

AppRegistry.registerComponent(appName, () => App);

messaging().setBackgroundMessageHandler(async ({ data: { title, message } }) => {
    console.log('in background');
    // Save the notification locally
    const notificationList = JSON.parse(await AsyncStorage.getItem('@SM_NOTIFICATIONS')) || [];
    notificationList.push({ title, message, isRead: false });
    await AsyncStorage.setItem('@SM_NOTIFICATIONS', JSON.stringify(notificationList));
});

Nothing happened beside the incoming notifications. I expected the code to save the incoming notifications in AsyncStorage.

Layout design in react native

$
0
0

I am trying to design below layout in react native.

I am not able to draw horizontal line as shown above. Some how I have drawn but margin on the right is not being appliedLAYOUT IN REACT NATIVE

Code

<View style={{ flexDirection: 'row' }}>
                    <Text style={styles.text}>
                        Search
                </Text>
                    <View style={styles.viewStyleForLine1}></View>
                </View>

Style

viewStyleForLine1: {
        borderWidth: 1,
        borderColor: '#cc0000',
        alignSelf: 'stretch',
        marginLeft: 5,
        marginRight: 5,
        width:"100%"
    },

More edit on centering the content

Here is how my View is

<View style={{ flexDirection: 'row' }}>
            <Text style={styles.text}>
             Search</Text>
            <View style={styles.viewStyleForLine1}></View>
            </View>

Style

text: {
        marginTop: 16,
        fontSize: 30,
        fontWeight: 'bold',
        color: '#cc0000',
        marginLeft: 15
    },

    viewStyleForLine1: {
        borderBottomWidth: 1,
        borderColor: '#cc0000',
        marginLeft: 5,
        alignItems:"center",      
        marginRight: 15,
        alignSelf:"center",
        flex:1
    },

What modification I should do?

What is the best way to call a GraphQL API in React Native

$
0
0

I'm using GraphQL API for my react native project. I would like to know some questions about GraphQL since I'm beginner of using it.

I found two methods of fetching data from GraphQL to react native application

  1. Using ApolloProvider to Fetch data
  2. Using Fetch Method ( Same like REST API's )

I want to know what is the correct way of doing GraphQL requests with react native application.

Once I use ApolloProvider and GraphQL Tags the response is in between Query Tags. But once I use normal fetch It will act as normal HTTP Request.

Normal Fetch Function to get GraphQL Data

fetch('http://snowtooth.moonhighway.com/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    query: 'query { allLifts { id name status } }',
  }),
})
  .then(response => response.json())
  .then(responseText => {
    this.setState({users_data: responseText.data.allLifts});
  })
  .catch(error => {});

This is the standard GraphQL using ApolloProvider and Tags

const query = gql`
        query {
             players {
                position
                name
                team
                jerseyNumber
                wonSuperBowl
            }
        }
`;

//Define your component
class PlayersList extends PureComponent {
    //Define your method for rendering each individual item
    _renderItem({item}) {
        //Return the UI
        //It will return the text green or red depending if that player won a super bowl or not.
        return (
            <TouchableOpacity style={styles.itemContainer}>
                <Text style={styles.itemText}>Position: {item.position}</Text>
                <Text style={styles.itemText}>Name: {item.name}</Text>
                <Text style={styles.itemText}>Team: {item.team}</Text>
                <Text style={styles.itemText}>Jersey Number: {item.jerseyNumber}</Text>
                <Text style={[styles.itemText, item.wonSuperBowl ? styles.wonSuperBowlText : styles.errorText]}>
                    Won Superbowl: {item.wonSuperBowl ? 'YES' : 'NO'}
                </Text>
            </TouchableOpacity>
        );
    }
    render() {
        //render your ui with the styles set for each ui element.
        return (
            <ScrollView style={styles.container}>
                {/*Can use an array to override styles for your UI elements.*/}
                <Text style={[styles.itemText, styles.headerText]}>Top 25 NFL Players List</Text>
                <Query query={query}>
                    {/* The props.children of the Query will be a callback with a response, and error parameter. */}
                    {(response, error) => {
                        if(error) {
                            console.log('Response Error-------', error);
                            return <Text style={styles.errorText}>{error}</Text>
                        }
                        //If the response is done, then will return the FlatList
                        if(response) {
                            console.log('response-data-------------', response);
                            //Return the FlatList if there is not an error.
                            return <FlatList 
                                        data={response.data.players}
                                        renderItem={(item) => this._renderItem(item)}
                                    />;
                        } 
                    }}
                </Query>
            </ScrollView>
        );
    }
}

I would like to know what is the best way of fetching data using GraphQL. If I do normal fetch what are the limitations ?

Can't resolve symbol android.support.v4.util.Pools in react-native-gesture-handler

$
0
0

I am working on react-native project.

After I update my modules by running 'npm install',

I cannot find class 'Pools' which located in 'android.support.v4.util' in 'react-native-gesture-handler'.

  1. Why Is this error occur?
  2. How can I fix this?

1.error (In case run "react-native run-android") -cmd

Task :react-native-gesture-handler:compileDebugJavaWithJavac FAILED
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:3: error: cannot find symbol
import android.support.v4.util.Pools;
                              ^
  symbol:   class Pools
  location: package android.support.v4.util
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:19: error: package Pools does not exist
  private static final Pools.SynchronizedPool<RNGestureHandlerEvent> EVENTS_POOL =
                            ^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:3: error: cannot find symbol
import android.support.v4.util.Pools;
                              ^
  symbol:   class Pools
  location: package android.support.v4.util
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:18: error: package Pools does not exist
  private static final Pools.SynchronizedPool<RNGestureHandlerStateChangeEvent> EVENTS_POOL =
                            ^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:20: error: package Pools does not exist
          new Pools.SynchronizedPool<>(TOUCH_EVENTS_POOL_SIZE);
                   ^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:19: error: package Pools does not exist
          new Pools.SynchronizedPool<>(TOUCH_EVENTS_POOL_SIZE);
                   ^
Note:D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerButtonViewManager.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors

2.React Native Environment Info:

System:
      OS: Windows 10
      CPU: (4) x64 Intel(R) Core(TM) i5-7500 CPU @ 3.40GHz
      Memory: 7.59 GB / 15.96 GB
    Binaries:
      Yarn: 1.15.2 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
      npm: 6.9.0 - C:\Program Files\nodejs\npm.CMD
    IDEs:
      Android Studio: Version  3.4.0.0 AI-183.5429.30.34.5452501

3.package.json

{
 "name": "project_y",
 "version": "0.0.1",
 "private": true,
 "scripts": {
 "start": "react-native run-android",
 "gradle-clean": "cd android & gradlew clean",
 "start-root": "react-native run-android --root",
 "test": "jest",
 "bundle": "react-native bundle --platform android --dev false --entry-file     
 index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/",
 "build": "cd android & gradlew assembleDebug"
 },
 "dependencies": {
  "axios": "^0.18.0",
  "moment": "^2.24.0",
  "prop-types": "^15.7.2",
  "react": "16.6.3",
  "react-native": "0.58.5",
  "react-native-android-open-settings": "^1.3.0",
  "react-native-custom-checkbox": "^1.5.2",
  "react-native-gesture-handler": "^1.0.16",
  "react-native-grid-list": "^1.0.9",
  "react-native-image-resizer": "^1.0.1",
  "react-native-kakao-logins": "^1.3.6",
  "react-native-linear-gradient": "^2.5.3",
  "react-native-picker-select": "^6.0.0",
  "react-native-shadow": "^1.2.2",
  "react-native-super-grid": "^3.0.3",
  "react-native-svg": "^9.2.4",
  "react-native-vector-icons": "^6.3.0",
  "react-native-webview": "^5.5.0",
  "react-navigation": "^3.3.2",
  "react-redux": "^6.0.1",
  "redux": "^4.0.1"
 },
 "devDependencies": {
  "babel-core": "7.0.0-bridge.0",
  "babel-jest": "24.1.0",
  "jest": "24.1.0",
  "metro-react-native-babel-preset": "0.52.0",
  "react-test-renderer": "16.6.3",
  "redux-devtools": "^3.5.0"
 },
 "jest": {
   "preset": "react-native"
 },
 "rnpm": {
  "assets": [
    "./assets/fonts/",
    "resources/fonts"
  ]
 }
}

4.build.gradle(app/)

apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false

android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion

defaultConfig {
    applicationId "com.projecty.projecty"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    versionCode 10
    versionName "1.9"
}
splits {
    abi {
        reset()
        enable enableSeparateBuildPerCPUArchitecture
        universalApk false  // If true, also generate a universal APK
        include "armeabi-v7a", "x86", "arm64-v8a"
    }
}
buildTypes {
    release {
        minifyEnabled enableProguardInReleaseBuilds
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
}
applicationVariants.all { variant ->
    variant.outputs.each { output ->

        def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3]
        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 'com.google.android.gms:play-services-base:12.0.0'
 implementation 'com.android.installreferrer:installreferrer:1.0'
 implementation 'com.igaworks.adbrix:abx-common-rm:+'

 implementation project(':react-native-webview')
 implementation project(':react-native-android-open-settings')
 implementation project(':react-native-kakao-logins')
 implementation project(':react-native-svg')
 implementation project(':react-native-linear-gradient')
 implementation project(':react-native-vector-icons')
 implementation project(':react-native-gesture-handler')

 implementation fileTree(dir: "libs", include: ["*.jar"])
 implementation "com.android.support:appcompat- 
 v7:${rootProject.ext.supportLibVersion}"
 compile(name: 'IgawSSP_v2.0.6a', ext: 'aar')
 repositories {
    flatDir {
        dirs 'libs'
    }
 }
implementation "com.facebook.react:react-native:+"  // From node_modules
}


task copyDownloadableDepsToLibs(type: Copy) {
 from configurations.compile
 into 'libs'
}

subprojects {
 repositories {
    mavenCentral()
    maven { url 
 'http://devrepo.kakao.com:8088/nexus/content/groups/public/' }
 }
}

5.build.gradle(android/)

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

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

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        flatDir {
            dirs 'libs'
        }
        maven {
            url 'https://dl.bintray.com/igaworks/AdbrixRmSDK'
        }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        mavenCentral()
        maven {
            url 'http://devrepo.kakao.com:8088/nexus/content/groups/public/'
        }


    }
}


task wrapper(type: Wrapper) {
    gradleVersion = '4.7'
    distributionUrl = distributionUrl.replace("bin", "all")
}

I expect the complete of build project.

react native navigator.geolocation.getCurrentPosition not working

$
0
0

I am using a real android device (version 5.1)

I am able to determine my position using react-native-maps (correct blue point position on map inside my app ) + I am able use google maps app and go to my position (GPS works).

I am using a big timeout, toggling enableHighAccuracy to true and false, remove options ... etc . all failed to get navigator.geolocation to get data.

Here is my code:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
};

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
};

navigator.geolocation.getCurrentPosition(success, error, options);

I am getting : ERROR(3): Location request timed out

How to add resource-id to android in react-native

$
0
0

I was trying to use firebase TestLab but it seems that it can only target resource-id. I had my elements like this:

<Input {...props} testID="usernameIput" />

But it seems that the testID is not mapped to the resource-id. If this is not the way to do it, then how can I get access to resource-id within react-native? If I can't what is the work around to add resource-id in android studio?


Dynamically fill some data in android/app/build.gradle (React Native ap)

$
0
0

For my react-native application I am using react-native-app-auth library.

I need to fill this info in build.gradle file, for android:

android {
  defaultConfig {
    manifestPlaceholders = [
      appAuthRedirectScheme: 'io.identityserver.demo'
    ]
  }
}

But appAuthRedirectScheme can be different for some roles of users. And I need to send this scheme directly from react-native components (when I get that scheme/url from another API).

Is there any way to do this?

Stop loading Webview in react native

$
0
0

I have react native project on Android platform. I have a Webview loaded from url. When user click any url, i want navigate to screen in my app and webview will stop loading. So in my onNavigationStateChange() function

  source = {{uri:this.props.htmlUrl}}
    ref='_webView'
    scrollEnabled={true}
    javaScriptEnabled={true}
    domStorageEnabled={true}
    onNavigationStateChange ={(navState)=>{
      //handle navigate another screen
       this.refs._webView.stopLoading();
    }}

It works. So when i go back, and click other url, I can not touch any url in webview. If someone meet the same issue, please help me. Thanks in advance.

Cannot connect to Apollo GraphQL server on Android Release [react native]

$
0
0
    httpURI = 'http://17.25.16.68:4000/graphql' //example
    const httpLink = createHttpLink({ uri: httpURI });
    const client = new ApolloClient({ link:httpLink, cache: new InMemoryCache() });

The connection works on debug mode, but when I run it on release, no connection is made.

Do I need to enable outgoing connections somewhere in the Android release config?

App crashes after calling setState in static method

$
0
0

After calling setState in navigationOptions the App crashes. This only happens on an Android device. Below my crashing code.

import React, { Component } from 'react';
import {
  Button,
  View,
  Platform,
  Text
} from 'react-native';
import { HeaderBackButton } from 'react-navigation-stack';

export default class Edit extends Component {
  static navigationOptions = ({ navigation: { state } }) => {
    return {
      title: 'add',
      gesturesEnabled: !state.params.isEditing,
      headerBackTitle: 'back',
      headerLeft: !state.params.isEditing(
        <HeaderBackButton
          backTitleVisible
          onPress={() => state.params.goBack()}
          title={Platform.OS === 'ios' ? 'back' : null}
        />
      ),
      headerRight: (
        <View style={Platform.OS !== 'ios'&& { padding: 12 }}>
          {state.params.isEditing ? (
            <Button onPress={() => state.params.finishEditing()} title="done" />
          ) : (
            <Button onPress={() => state.params.beginEditing()} title="edit" />
          )}
        </View>
      ),
    };
  };

  state = {
    isLoading: true,
    isEditing: false,
    alreadyScanned: true,
  };

  componentDidMount() {
    this.setInitialState();
  }

  setInitialState = () => {
    const {
      navigation: {
        setParams,
        state: { params },
      },
      navigation,
    } = this.props;

    setParams({
      isEditing: this.state.isEditing,
      finishEditing: this.finishEditing,
      beginEditing: this.beginEditing,
      canGoBack: params.goBack,
      goBack: navigation.goBack,
    });
  };

  beginEditing = async () => {
    this.setState({
      isEditing: true,
    });
    await this.props.navigation.setParams({
      isEditing: true,
    });
  };

  finishEditing = async () => {
    this.setState({ isEditing: false });
    await this.props.navigation.setParams({
      isEditing: false,
    });
  };

  render() {
    const {isEditing} = this.state;
    return (
      <View
        style={{
          flex: 1,
          backgroundColor: isEditing ? 'green' : 'red'
        }}>
        <Text>is editing: {isEditing}</Text>
      </View>
    );
  }
}

I'm not quite sure why this code makes my app crash, because it did work before.

Expo Snack can't resolve the react-navigation module for some reason.. So here is my crashing code.

Project dependencies

"dependencies": {
    "expo": "^35.0.0",
    "expo-asset": "~7.0.0",
    "expo-barcode-scanner": "~7.0.0",
    "expo-camera": "~7.0.0",
    "expo-constants": "~7.0.0",
    "expo-font": "~7.0.0",
    "expo-localization": "~7.0.0",
    "expo-permissions": "~7.0.0",
    "react": "16.11.0",
    "react-dom": "16.11.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz",
    "react-native-elements": "^1.2.6",
    "react-native-gesture-handler": "~1.3.0",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^1.10.3",
  }

Environment

react native: check Android background activities setting

$
0
0

I want my application to check whether its background activity is enabled in the Android settings.

Settings => Apps & notifications => Advanced => Apps background activities

I'm aware about the react-native-device-info package but I didn't see any method relating to the background activities.

How can I achieve that ?

react native build error: package android.support.annotation does not exist

$
0
0

I had to completely rewrite the question.

I have a react native android app. When I built the apk file with ./gradlew assembleRelease -x bundleReleaseJsAndAssets, it went fine, but after that it stopped compiling at all. Even react-native run-android is not working anymore.

What I found so far: First, the error is this

Task :app:processDebugResources FAILED
resource android:attr/fontVariationSettings not found.
resource android:attr/ttcIndex not found.

If I add these lines to gradle.properties,

android.useAndroidX=true
android.enableJetifier=true

the error changes. Now it's this

Task :@JWWon_react-native-universal-pedometer:compileDebugJavaWithJavac FAILED

error: package android.support.annotation does not exist
import android.support.annotation.Nullable;
                                 ^
cannot find symbol
  private void sendPedometerUpdateEvent(@Nullable WritableMap params) {
                                         ^
  symbol:   class Nullable
  location: class BMDPedometerModule

The problem is not with the library though. If I remove it from the project, it start complaining about another one. To get it to compile, I have to remove 7 libraries. An example:

Task :@react-native-community_netinfo:compileDebugJavaWithJavac FAILED
error: package android.support.v4.net does not exist
import android.support.v4.net.ConnectivityManagerCompat;
error: cannot find symbol
    promise.resolve(ConnectivityManagerCompat.isActiveNetworkMetered(getConnectivityManager()));
                    ^
  symbol:   variable ConnectivityManagerCompat
  location: class ConnectivityReceiver
2 errors

then if I remove another, this happens:

Task :react-native-camera-kit:compileDebugJavaWithJavac FAILED
package android.support.annotation does not exist
import android.support.annotation.ColorInt;
                                 ^
package android.support.annotation does not exist
import android.support.annotation.IntRange;
                                 ^
...
92 errors

So it will compile if I remove 7 libraries from the project. They are:

react-native-camera-kit @react-native-community_netinfo react-native-push-notification react-native-sensors @JWWon_react-native-universal-pedometer react-native-keep-awake react-native-toast-native

Without them, it compiles perfectly. So there's a bigger problem that doesn't let it work. 2 days ago, all of those libraries were working perfectly with no problem. But now something crushes it.

How to make sure JS Modules are loaded before sending message from ReactActivity via JS bridge?

$
0
0

In my react app the MainActivity(subclass of ReactActivity) is launched from the subclass of BroadcastReceiver. From the MainActivity::onCreate method a message to JS Module is emitted through JS bridge which gets lost. From the logs it looks like the JS Module gets mounted after the message is sent from MainActivity::onCreate() method.

ExampleReceiver.java

public class ExampleReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, ANService.class);
        service.putExtras(intent);
    service.setClassName("com.example", "com.example.MainActivity");
        service.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(service);
    }
}

MainActivity.java

public class MainActivity extends ReactActivity {
    ...
    ...
  @Override
  protected void onCreate (Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Log.d(TAG, "onCreate -> MainActivity -> ReactActivity");
      try {
      JSONObject data = BundleJSONConverter.convertToJSON(getIntent().getExtras());
      Log.d(TAG, data.toString());
          getReactInstanceManager().getCurrentReactContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("onExampleMessage", data.toString());
      } catch (Exception e) {
          System.err.println("Exception when handling notification openned. " + e);
      }
  }
}

ExampleJSComponent.js

export default class ExampleJSComponent extends Component
{
    componentDidMount() {
    console.log('ExampleJSComponent componentDidMount');

    DeviceEventEmitter.addListener('onExampleMessage', async function(e) {
        const obj = JSON.parse(e);
        console.log(obj);
    });
    }
}

Adb logcat Logs:
...
...
D MainActivity: onCreate -> MainActivity -> ReactActivity
...
...
I ReactNativeJS: in index.js
I ReactNativeJS: ExampleJSComponent componentDidMount


The following line does not ensure the JS components are mounted.

getReactInstanceManager().getCurrentReactContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)

How to make sure the JS component is mounted before sending message from the MainActivity::onCreate method ?


React Native Web crashes with aws-amplify

$
0
0

I'm using aws-amplify in my app for iOS, Android and Web, but when I import aws-amplify

import 'aws-amplify';

Android and iOS work fine but the web app crashes with the error message:

Failed to compile
Can't reexport the named export 'BREAK' from non EcmaScript module (only default export is available)

Does anyone know the solution to this problem?

Expo app runs on ios and emulator but not on android device

$
0
0

Expo app will build and run correctly on ios simulator, ios device, and android emulator. but when I build an apk and run on an android device the app freezes after login and will not respond. I'm fairly new to react-native and development in general so I'm not sure what I would be doing wrong?

Android, change string and reload activity

$
0
0

We have our api_host string set in a java file.

  • For testing purpose, we want to be able to change the api_host at runtime through a ui (provide a textinput where you can edit the api_host variable)

  • Also we have to consider recreating the activity

    Because we are initializing a webview or React-Native view at onCreate method like the following: mReactRootView.startReactApplication(api_host)

Or just fresh implementation of managing api_host is welcome if it can provide the capability of changing the api_host value at runtime through a ui.

clean react native project immediately crashes on real android device debug mode

$
0
0

I have a strange problem with React Native. I have checked it with several versions of RN for example 0.55.0 to 0.61.2 and tried several solutions but none of them solved my problem. The problem is when I install debug apk on my real device(samsung s7 edge - android 8.0.0), when the bundle load, app immediately crashes. But if I install signed release apk, it works fine. It is so wired.

For example I did:

react-native init AwesomeProject
cd AwesomeProject
react-native run-android

Then app crashed immediately, Though it works properly on emulator.

here is logcat logs:

10-23 00:39:14.840: D/StorageManagerService(3655): getExternalStorageMountMode : final mountMode=1, uid : 10821, packageName : com.awesomeproject
10-23 00:39:14.840: I/ApplicationPolicy(3655): isApplicationExternalStorageWhitelisted:com.awesomeproject user:0
10-23 00:39:14.840: D/ActivityManager(3655): package  com.awesomeproject, user - 0 is SDcard whitelisted
10-23 00:39:14.840: I/ApplicationPolicy(3655): isApplicationExternalStorageBlacklisted:com.awesomeproject user:0
10-23 00:39:14.870: I/ActivityManager(3655): Start proc 22662:com.awesomeproject/u0a821 for activity com.awesomeproject/.MainActivity
10-23 00:39:14.877: I/SELinux(22662): SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.awesomeproject 
10-23 00:39:14.953: I/ActivityManager(3655): START u0 {act=android.intent.action.MAIN typ=null flg=0x10200000 cmp=ComponentInfo{com.awesomeproject/com.awesomeproject.MainActivity}} from uid 10068
10-23 00:39:14.956: D/ActivityManagerPerformance(3655): Received MSG_CFMS_HINT_AMS_SWITCH pkgName: com.awesomeproject
10-23 00:39:14.967: D/ViewRootImpl@1d7ab40[awesomeproject](3655): setView = DecorView@d5d3be[awesomeproject] TM=true MM=false
10-23 00:39:14.967: D/ViewRootImpl@1d7ab40[awesomeproject](3655): setView = DecorView@d5d3be[awesomeproject] TM=true MM=false
10-23 00:39:14.971: I/ActivityManager(3655): DSS on for com.awesomeproject and scale is 1.0
10-23 00:39:14.973: V/WindowManager(3655): Relayout Window{2819a79 u0 Splash Screen com.awesomeproject}: viewVisibility=0 req=1080x1848 WM.LayoutParams{(0,0)(fillxfill) sim=#20 ty=3 fl=#81830118 pfl=0x20011 wanim=0x10302fd vsysui=0x600 needsMenuKey=2 colorMode=0 naviIconColor=0}
10-23 00:39:14.975: I/SurfaceFlinger(3197): id=592 createSurf (1080x1920),1 flag=404, Splash Screen com.awesomeproject#0
10-23 00:39:15.001: V/WindowManager(3655): finishDrawingLocked: mDrawState=COMMIT_DRAW_PENDING Window{2819a79 u0 Splash Screen com.awesomeproject} in Surface(name=Splash Screen com.awesomeproject)
10-23 00:39:15.002: D/ActivityManager(3655): applyOptionsLocked, ANIM_CUSTOM_SCALE_UP, task.getRootActivity() : ActivityRecord{6b7a94b u0 com.awesomeproject/.MainActivity t9606}, task.getTaskToReturnTo() : 1
10-23 00:39:15.010: D/GameManagerService(3655): handleForegroundChange(). pkgName: com.awesomeproject, clsName: com.awesomeproject.MainActivity,FgActivityName:com.awesomeproject/.MainActivity
10-23 00:39:15.011: D/GameManagerService(3655): notifyResumePause(). pkg: com.awesomeproject, type: 4, isMinimized: false, isTunableApp: false
10-23 00:39:15.011: D/MARsPolicyManager(3655): onPackageResumedFG pkgName = com.awesomeproject, userId = 0
10-23 00:39:15.029: D/GamePkgDataHelper(3655): getGamePkgDataIncServer(). com.awesomeproject
10-23 00:39:15.029: D/GamePkgDataHelper(3655): getGamePkgDataIncServer(). com.awesomeproject
10-23 00:39:15.030: D/GameManagerService(3655): identifyGamePackage. com.awesomeproject
10-23 00:39:15.030: D/GamePkgDataHelper(3655): getGamePkgData(). com.awesomeproject
10-23 00:39:15.036: D/GamePkgDataHelper(3655): getGamePkgData(). com.awesomeproject
10-23 00:39:15.037: D/GameManagerService(3655): identifyGamePackage. com.awesomeproject
10-23 00:39:15.037: D/GamePkgDataHelper(3655): getGamePkgData(). com.awesomeproject
10-23 00:39:15.045: D/SoLoader(22662): adding application source: com.facebook.soloader.DirectorySoSource[root = /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64 flags = 0]
10-23 00:39:15.046: D/SoLoader(22662): adding backup source from : com.facebook.soloader.ApkSoSource[root = /data/data/com.awesomeproject/lib-main flags = 1]
10-23 00:39:15.047: D/SoLoader(22662): Preparing SO source: com.facebook.soloader.DirectorySoSource[root = /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64 flags = 0]
10-23 00:39:15.047: D/SoLoader(22662): Preparing SO source: com.facebook.soloader.ApkSoSource[root = /data/data/com.awesomeproject/lib-main flags = 1]
10-23 00:39:15.048: V/fb-UnpackingSoSource(22662): locked dso store /data/user/0/com.awesomeproject/lib-main
10-23 00:39:15.050: I/fb-UnpackingSoSource(22662): dso store is up-to-date: /data/user/0/com.awesomeproject/lib-main
10-23 00:39:15.050: V/fb-UnpackingSoSource(22662): releasing dso store lock for /data/user/0/com.awesomeproject/lib-main
10-23 00:39:15.052: W/System.err(22662):    at com.awesomeproject.MainApplication.initializeFlipper(MainApplication.java:61)
10-23 00:39:15.052: W/System.err(22662):    at com.awesomeproject.MainApplication.onCreate(MainApplication.java:46)
10-23 00:39:15.053: W/System.err(22662): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.flipper.ReactNativeFlipper" on path: DexPathList[[zip file "/data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/base.apk"],nativeLibraryDirectories=[/data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64, /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]
10-23 00:39:15.056: D/GameManagerService(3655): identifyGamePackage. com.awesomeproject
10-23 00:39:15.056: D/GamePkgDataHelper(3655): getGamePkgData(). com.awesomeproject
10-23 00:39:15.061: D/GameManagerService(3655): identifyGamePackage. com.awesomeproject
10-23 00:39:15.061: D/GamePkgDataHelper(3655): getGamePkgData(). com.awesomeproject
10-23 00:39:15.061: D/SurfaceFlinger(3197):        HWC | 7df8a2dcc0 | 0000 | 0020 | 00 | 0105 | RGBA_8888   |    0.0,    0.0, 1080.0, 1920.0 |  112,  129,  828, 1402 | Splash Screen com.awesomeproject#0
10-23 00:39:15.090: D/SoLoader(22662): libjscexecutor.so not found on /data/data/com.awesomeproject/lib-main
10-23 00:39:15.090: D/SoLoader(22662): libjscexecutor.so found on /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64
10-23 00:39:15.140: D/SurfaceFlinger(3197):       GLES | 7df8a2dcc0 | 0000 | 0020 | 00 | 0105 | RGBA_8888   |    0.0,    0.0, 1080.0, 1920.0 |   27,   31, 1020, 1796 | Splash Screen com.awesomeproject#0
10-23 00:39:15.160: D/MdnieScenarioControlService(3655):  packageName : com.awesomeproject    className : com.awesomeproject.MainActivity
10-23 00:39:15.178: I/zygote64(22662): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/base.apk"],nativeLibraryDirectories=[/data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64, /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]
10-23 00:39:15.179: I/zygote64(22662): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/base.apk"],nativeLibraryDirectories=[/data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64, /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]
10-23 00:39:15.179: I/zygote64(22662): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/base.apk"],nativeLibraryDirectories=[/data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64, /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]
10-23 00:39:15.226: V/WindowManager(3655): Relayout Window{acc6470 u0 com.awesomeproject/com.awesomeproject.MainActivity}: viewVisibility=0 req=1080x1848 WM.LayoutParams{(0,0)(fillxfill) sim=#110 ty=1 fl=#81810100 pfl=0x20000 wanim=0x10302fd vsysui=0x600 needsMenuKey=2 colorMode=0 naviIconColor=0}
10-23 00:39:15.228: I/SurfaceFlinger(3197): id=593 createSurf (1080x1920),1 flag=404, com.awesomeproject/com.awesomeproject.MainActivity#0
10-23 00:39:15.242: D/libGLESv1(22662): STS_GLApi : DTS, ODTC are not allowed for Package : com.awesomeproject
10-23 00:39:15.261: V/InputMethodManager(22662): Starting input: tba=android.view.inputmethod.EditorInfo@3926903 nm : com.awesomeproject ic=null
10-23 00:39:15.262: V/InputMethodManagerService(3655): windowGainedFocus : reason=WINDOW_FOCUS_GAIN client=android.os.BinderProxy@927ec22 inputContext=null missingMethods= attribute=android.view.inputmethod.EditorInfo@e6b579c nm = com.awesomeproject controlFlags=#104 softInputMode=#110 windowFlags=#81810100
10-23 00:39:15.288: V/WindowManager(3655): finishDrawingLocked: mDrawState=COMMIT_DRAW_PENDING Window{acc6470 u0 com.awesomeproject/com.awesomeproject.MainActivity} in Surface(name=com.awesomeproject/com.awesomeproject.MainActivity)
10-23 00:39:15.293: D/InputEventReceiver(3655): channel '2819a79 Splash Screen com.awesomeproject (client)' ~ Disposing input event receiver.
10-23 00:39:15.293: D/InputEventReceiver(3655): channel '2819a79 Splash Screen com.awesomeproject (client)' ~NativeInputEventReceiver.
10-23 00:39:15.309: D/SurfaceFlinger(3197):        HWC | 7df8a2dcc0 | 0000 | 0020 | 00 | 0100 | RGBA_8888   |    0.0,    0.0, 1080.0, 1920.0 |    0,    0, 1080, 1920 | Splash Screen com.awesomeproject#0
10-23 00:39:15.318: V/InputMethodManager(22662): Starting input: tba=android.view.inputmethod.EditorInfo@ca7d080 nm : com.awesomeproject ic=null
10-23 00:39:15.325: D/SurfaceFlinger(3197):        HWC | 7df47fddc0 | 0000 | 0020 | 00 | 0100 | RGBA_8888   |    0.0,    0.0, 1080.0, 1920.0 |    0,    0, 1080, 1920 | com.awesomeproject/com.awesomeproject.MainActivity#0
10-23 00:39:15.325: I/WindowManager(3655): Destroying surface Surface(name=Splash Screen com.awesomeproject) called by com.android.server.wm.WindowStateAnimator.destroySurface:2501 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:985 com.android.server.wm.WindowState.destroyOrSaveSurfaceUnchecked:3680 com.android.server.wm.WindowState.destroySurface:3628 com.android.server.wm.AppWindowToken.destroySurfaces:722 com.android.server.wm.AppWindowToken.destroySurfaces:706 com.android.server.wm.WindowState.onExitAnimationDone:5335 com.android.server.wm.WindowStateAnimator.stepAnimationLocked:550 
10-23 00:39:15.325: I/SurfaceFlinger(3197): id=592 Removed Splash Screen com.awesomeproject#0 (4/7)
10-23 00:39:15.331: I/SurfaceFlinger(3197): id=592 Removed Splash Screen com.awesomeproject#0 (-2/7)
10-23 00:39:15.337: I/Layer(3197): id=592 onRemoved Splash Screen com.awesomeproject#0 
10-23 00:39:15.345: I/ActivityManager(3655): Displayed com.awesomeproject/.MainActivity: +361ms
10-23 00:39:15.355: D/SurfaceFlinger(3197):        HWC | 7df47fddc0 | 0000 | 0020 | 00 | 0100 | RGBA_8888   |    0.0,    0.0, 1080.0, 1920.0 |    0,    0, 1080, 1920 | com.awesomeproject/com.awesomeproject.MainActivity#0
10-23 00:39:15.440: D/SurfaceFlinger(3197):        HWC | 7df47fddc0 | 0000 | 0020 | 00 | 0100 | RGBA_8888   |    0.0,    0.0, 1080.0, 1920.0 |    0,    0, 1080, 1920 | com.awesomeproject/com.awesomeproject.MainActivity#0
10-23 00:39:15.440: D/SoLoader(22662): libreactnativejni.so not found on /data/data/com.awesomeproject/lib-main
10-23 00:39:15.440: D/SoLoader(22662): libreactnativejni.so found on /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64
10-23 00:39:15.443: D/SoLoader(22662): libfb.so not found on /data/data/com.awesomeproject/lib-main
10-23 00:39:15.443: D/SoLoader(22662): libfb.so found on /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64
10-23 00:39:15.444: D/SoLoader(22662): libfb.so not found on /data/data/com.awesomeproject/lib-main
10-23 00:39:15.444: D/SoLoader(22662): libfb.so found on /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64
10-23 00:39:15.444: I/zygote64(22662): Thread[24,tid=22718,Native,Thread*=0x7cfc286e00,peer=0x12fd5a20,"create_react_context"] recursive attempt to load library "/data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64/libfb.so"
10-23 00:39:15.489: D/MdnieScenarioControlService(3655):  packageName : com.awesomeproject    className : com.awesomeproject.MainActivity
10-23 00:39:15.629: D/SoLoader(22662): libyoga.so not found on /data/data/com.awesomeproject/lib-main
10-23 00:39:15.630: D/SoLoader(22662): libyoga.so found on /data/app/com.awesomeproject-EThs6uZ8OF5VI7aipjsTOg==/lib/arm64
10-23 00:39:16.055: A/DEBUG(22734): pid: 22662, tid: 22721, name: mqt_native_modu  >>> com.awesomeproject <<<
10-23 00:39:17.162: W/ActivityManager(3655): crash : com.awesomeproject,0
10-23 00:39:17.163: W/ActivityManager(3655):   Force finishing activity com.awesomeproject/.MainActivity
10-23 00:39:17.165: W/MultiScreenManagerService(3655): moveTaskBackToDisplayIfNeeded(): root activity or app is null, task=TaskRecord{9d01df6d0 #9606 A=com.awesomeproject U=0 StackId=1 sz=1}, rootActivity=null
10-23 00:39:17.173: I/ActivityManager(3655): Showing crash dialog for package com.awesomeproject u0
10-23 00:39:17.222: D/ViewRootImpl@21c7092[awesomeproject](3655): setView = DecorView@f14f719[awesomeproject] TM=true MM=false
10-23 00:39:17.241: V/WindowManager(3655): Relayout Window{da21660 u0 Application Error: com.awesomeproject}: viewVisibility=0 req=1015x442 WM.LayoutParams{(0,0)(wrapxwrap) gr=#11 sim=#120 ty=2003 fl=#1820002 pfl=0x110 fmt=-3 wanim=0x10302ec surfaceInsets=Rect(6, 6 - 6, 6) needsMenuKey=2 colorMode=0 naviIconColor=0}
10-23 00:39:17.244: I/SurfaceFlinger(3197): id=595 createSurf (1027x454),1 flag=4, Application Error: com.awesomeproject#0
10-23 00:39:17.273: I/WindowManager(3655): WIN DEATH: Window{acc6470 u0 com.awesomeproject/com.awesomeproject.MainActivity}
10-23 00:39:17.274: I/WindowManager(3655): Destroying surface Surface(name=com.awesomeproject/com.awesomeproject.MainActivity) called by com.android.server.wm.WindowStateAnimator.destroySurface:2501 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:985 com.android.server.wm.WindowState.removeImmediately:2404 com.android.server.wm.WindowState.removeIfPossible:2606 com.android.server.wm.WindowState.-wrap1:0 com.android.server.wm.WindowState$DeathRecipient.binderDied:3151 android.os.BinderProxy.sendDeathNotice:843 <bottom of call stack> 
10-23 00:39:17.278: I/SurfaceFlinger(3197): id=593 Removed com.awesomeproject/com.awesomeproject.MainActivity#0 (1/6)
10-23 00:39:17.278: I/SurfaceFlinger(3197): id=593 Removed com.awesomeproject/com.awesomeproject.MainActivity#0 (-2/6)
10-23 00:39:17.282: I/ActivityManager(3655): Process com.awesomeproject (pid 22662) has died: vis  +99TOP (133,1567)
10-23 00:39:17.285: V/WindowManager(3655): finishDrawingLocked: mDrawState=COMMIT_DRAW_PENDING Window{da21660 u0 Application Error: com.awesomeproject} in Surface(name=Application Error: com.awesomeproject)
10-23 00:39:17.286: I/SurfaceFlinger(3197): id=593 Removed com.awesomeproject/com.awesomeproject.MainActivity#0 (-2/6)
10-23 00:39:17.289: I/Layer(3197): id=593 onRemoved com.awesomeproject/com.awesomeproject.MainActivity#0 
10-23 00:39:17.326: D/SurfaceFlinger(3197):       GLES | 7df0377180 | 0000 | 0000 | 00 | 0105 | RGBA_8888   |    0.0,    0.0, 1027.0,  454.0 |   68,  787, 1010, 1204 | Application Error: com.awesomeproject#0
10-23 00:39:17.334: D/PackageManager(3655): getComponentMetadataForIconTray : com.awesomeproject.MainActivity does not exist in mServices
10-23 00:39:17.334: D/PackageManager(3655): getComponentMetadataForIconTray : com.awesomeproject.MainActivity does not exist in mProviders
10-23 00:39:17.334: D/PackageManager(3655): getComponentMetadataForIconTray : com.awesomeproject.MainActivity does not exist in mReceivers
10-23 00:39:17.335: D/ApplicationPackageManager(4073): updateItemMetaDataForFixedIconScale: package: com.awesomeproject
10-23 00:39:17.335: D/PackageManager(3655): getSelectedMetaData : packageName(com.awesomeproject) or Metadata strings {[Ljava.lang.String;@a4708a8}
10-23 00:39:17.336: I/ApplicationPackageManager(4073): load=com.awesomeproject, bg=144-144, dr=144-144, forDefault=true, density=0
10-23 00:39:17.338: I/ApplicationPackageManager(4073): load=com.awesomeproject-crop, bg=114-114, dr=144-144
10-23 00:39:17.341: W/PkgUtils(17655): p: com.awesomeproject, u:0
10-23 00:39:17.358: D/SurfaceFlinger(3197):       GLES | 7df0377180 | 0000 | 0000 | 00 | 0105 | RGBA_8888   |    0.0,    0.0, 1027.0,  454.0 |   48,  778, 1031, 1213 | Application Error: com.awesomeproject#0
10-23 00:39:17.452: D/SurfaceFlinger(3197):    22,  767, 1058, 1225 | Application Error: com.awesomeproject#0
10-23 00:39:17.460: D/SurfaceFlinger(3197):        HWC | 7df0377180 | 0000 | 0000 | 00 | 0105 | RGBA_8888   |    0.0,    0.0, 1027.0,  454.0 |   20,  767, 1058, 1226 | Application Error: com.awesomeproject#0
10-23 00:39:21.455: D/SurfaceFlinger(3197): 5 | RGBA_8888   |    0.0,    0.0, 1027.0,  454.0 |   26,  769, 1053, 1223 | Application Error: com.awesomeproject#0

here is my package.json:

{
  "name": "AwesomeProject",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.2"
  },
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/runtime": "^7.6.3",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

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

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

apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

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

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

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and mirrored here.  If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
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.awesomeproject"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    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 fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/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'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

Cause of a OutOfMemoryError with React native Android

$
0
0

I'm developping an app with React native and my last version in release mode crashes after 20-30 seconds with the following generated logcat:

02-19 23:52:10.777 32717-32717/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: my.app, PID: 32717
    java.lang.OutOfMemoryError: std::bad_alloc
        at com.facebook.react.bridge.WritableNativeArray.pushInt(Native Method)
        at com.facebook.react.modules.core.Timing$TimerFrameCallback.doFrame(Timing.java:89)
        at com.facebook.react.modules.core.ReactChoreographer$ReactChoreographerDispatcher.doFrame(ReactChoreographer.java:134)
        at com.facebook.react.modules.core.ChoreographerCompat$FrameCallback$1.doFrame(ChoreographerCompat.java:105)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:909)
        at android.view.Choreographer.doCallbacks(Choreographer.java:723)
        at android.view.Choreographer.doFrame(Choreographer.java:655)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6938)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

The app never crashes in dev mode.

How can I know what causes this? Is there a leak somewhere? What steps are to be followed to know more about it?

Viewing all 29599 articles
Browse latest View live


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