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

React Native 'run-android' mac issue

$
0
0

I have a react-native project that successfully runs on iOS emulator however, when running react-native run-android I get the following error:

error Failed to install the app. Make sure you have the Android development environment set up

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

I have downloaded Android studio, setup a virtual device, installed necessary JDK.

How can I resolve?

Full error message:

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:preDebugBuild'.
> Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
   > Could not resolve project :react-native-camera.
     Required by:
         project :app
      > Cannot choose between the following variants of project :react-native-camera:
          - generalDebugRuntimeElements
          - mlkitDebugRuntimeElements
        All of them match the consumer attributes:
          - Variant 'generalDebugRuntimeElements' capability VerizonApp:react-native-camera:unspecified:
              - Unmatched attributes:
                  - Found com.android.build.api.attributes.VariantAttr 'generalDebug' but wasn't required.
                  - Found react-native-camera 'general' but wasn't required.
              - Compatible attributes:
                  - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
                  - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
                  - Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.
          - Variant 'mlkitDebugRuntimeElements' capability VerizonApp:react-native-camera:unspecified:
              - Unmatched attributes:
                  - Found com.android.build.api.attributes.VariantAttr 'mlkitDebug' but wasn't required.
                  - Found react-native-camera 'mlkit' but wasn't required.
              - Compatible attributes:
                  - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
                  - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
                  - Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.

Unable to build React-Native project in android studio

$
0
0

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

React Native: Resize custom UI component

$
0
0

I've built a very simple native Android UI component and I want to update the size of its child view when a button from my react native project is clicked. To be more precise, when this button is clicked then I send a command to my SimpleViewManager which in turn calls the resizeLayout() of my custom view.

I can verify that the resizeLayout() is properly called but the layout is not resized until I rotate the phone. Obviously, changing the device's orientation triggers the draw() of my custom view but so does the invalidate() which I explicitly call.

Other layout changes like changing the background color instead of resizing it work fine.

My custom component looks like this:

public class CustomComponent extends RelativeLayout {
    public CustomComponent(Context context) {
        super(context);
        init();
    }

    public CustomComponent(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomComponent(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        inflate(getContext(), R.layout.simple_layout, this);
    }

    public void resizeLayout(){
        LinearLayout childLayout = (LinearLayout) findViewById(R.id.child_layout);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) childLayout.getLayoutParams();
        layoutParams.height = 50;
        layoutParams.width= 50;
        childLayout.setLayoutParams(layoutParams);

        invalidate();
    }
}

and the simple_layout.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/child_layout"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:background="#ffee11"/>
</RelativeLayout>

Any help would be greatly appreciated.

You need to call create() at least once to create the singleton

$
0
0

I'm working on Geolocation Background Task,when I'll be run the app is everything ok, but when close or restart the app the message is showing.

I´m actually using this package for background geolocation https://github.com/mauron85/react-native-background-geolocation

And OneSignal SDK for react native too.

System: OS: Windows 10 CPU: (4) x64 Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz Memory: 3.86 GB / 11.88 GB Binaries: Node: 10.16.1 - C:\Program Files\nodejs\node.EXE Yarn: 1.17.3 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 6.12.0 - C:\Program Files\nodejs\npm.CMD SDKs: Android SDK: API Levels: 19, 23, 25, 26, 27, 28, 29 Build Tools: 26.0.3, 28.0.3, 29.0.1 System Images: android-23 | Intel x86 Atom, android-23 | Intel x86 Atom_64, android-23 | Google APIs Intel x86 Atom, android-23 | Google APIs Intel x86 Atom_64, android-29 | Intel x86 Atom, android-29 | Intel x86 Atom_64, android-29 | Google APIs Intel x86 Atom, android-29 | Google APIs Intel x86 Atom_64, android-29 | Google Play Intel x86 Atom, android-29 | Google Play Intel x86 Atom_64
IDEs: Android Studio: Version 3.5.0.0 AI-191.8026.42.35.5900203 npmPackages: react: 16.8.6 => 16.8.6 react-native: ^0.60.5 => 0.60.6

I´m uninstallin both, OneSignal and background geolocation and still showing the message.

Opening deeplink in webbrowser to React-Native application

$
0
0

I have been trying to open an application through a web browser on my Android phones (both emulator and psychical device). Anytime when I put 'mydeeplink://people/0' as URL it just starts searching on google for the query instead of opening the app.

I personally think that I didn't configure one of the Google flags correctly. I left it all on default, because I didn't found anybody mentioning flags corresponding to deep links on the internet.

I already tried adding node-tools to the intent-filter after 'android:label="filter_react_native"'

I followed a tutorial from this website, however it seems to be outdated

this is my code:

AndroidManifest.xml:

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

<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: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>
    <intent-filter android:label="filter_react_native" 
     android:autoVerify="true">
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <data android:scheme="mydeeplink" android:host="people" />
  </intent-filter>
  </activity>
  <activity 
  android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>

 </manifest> 

index.android.js:

 // index.ios.js or index.android.js
 import { AppRegistry } from 'react-native';
 import Router from './router';
 AppRegistry.registerComponent('mydeeplink', () => Router);

home.js:

import React from 'react';
import { Platform, Text, Linking } from 'react-native';
class Home extends React.Component {
static navigationOptions = { // A
title: 'Home',
};
componentDidMount() { // B
 if (Platform.OS === 'android') {
  Linking.getInitialURL().then(url => {
  this.navigate(url);
});
} else {
  Linking.addEventListener('url', this.handleOpenURL);
}
}

componentWillUnmount() { // C
Linking.removeEventListener('url', this.handleOpenURL);
}
handleOpenURL = (event) => { // D
this.navigate(event.url);
}
navigate = (url) => { // E
const { navigate } = this.props.navigation;
const route = url.replace(/.*?:\/\//g, '');
const id = route.match(/\/([^\/]+)\/?$/)[1];
const routeName = route.split('/')[0];

if (routeName === 'people') {
  navigate('People', { id, name: 'chris' })
};
}
render() {
return <Text>Hello from Home!</Text>;
}
}
export default Home;

router.js:

       import React from 'react';
 import {
    AppRegistry,
    Text,
    }  from 'react-native';

  import { createStackNavigator } from 'react-navigation-stack';
  import { createAppContainer } from 'react-navigation';
  import Home from './home';
  import People from './people';
  const Router = createStackNavigator(
   {
      Home: Home,
      Details: People,
   },
   {
       initialRouteName: 'Home',
   }
 ) ;


const AppContainer = createAppContainer(Router);

export default class App extends React.Component{
     render(){
         return <AppContainer/>
     }
  }

It's expected to open my React-Native app and open a picture of Leela. Currently the query just searched for the query on the world wide web in google chrome on both emulator as physical device

Why Splash screen keeps appearing in the background after Login screen loaded?

$
0
0

I'm setting the Splash screen icon and color through app.json:

When i tried to test the app on Android emulator it work properly, but after executing the apk the issues seems to appear again

Here is the splash screen code snippet from app.json file:

"platforms": [
    "ios",
    "android"
],
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"splash": {
    "image": "./assets/splash.png",
    "resizeMode": "contain",
    "backgroundColor": "#ffd525"
}

I expected the Login screen to appear as:

enter image description here

But it keeps appearing as:

enter image description here

Dependencies used:

"dependencies": {
    "expo": "^32.0.0",
    "native-base": "^2.12.1",
    "react": "16.5.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk- 
    32.0.0.tar.gz",
    "react-native-paper": "^2.15.2",
    "react-navigation": "3.1.2"
}

How to have React Native project versions seamless across project and platforms

$
0
0

It is very annoying to change build version of my React Native (not Expo) application every time I build it.

It needs to be changed in at leats 4 places at moment:

  • /android/app/build.gradle
  • /ios/projectname/Info.plist
  • package.json
  • My config file (But I think I can handle this by loading it from package.json)

Is there any way to automatize this? For example every place gets updates when package.json version changes?

You have a release in production that hasn't been rolled out

$
0
0

I am trying to release my first app on android.

It's passed the review, and I'm ready to roll out the production track.

In App Releases, I click on Edit Release on the Production Track which says

"You have a release in production that hasn't been rolled out"

I hit review and I get an error

"You should either add a new APK or deactivate an existing APK to create a new release."

I only have 1 APK, and if I disable it, I cannot launch the app.

What am I doing wrong???


React Native + Expo fetch cache-control

$
0
0

I am building android app using react native expo integrated with redux. The API is called using fetch method, but always the cached result is displayed. Cache-Control header doesn't go with request. I've tried two types of header definition;

 var myHeaders = new Headers();
 myHeaders.set('Accept', 'application/json');
 myHeaders.set('Content-Type', 'application/json');
 myHeaders.set('Cache-Control', 'no-cache');

 fetch(
   "http://192.168.1.71:3000/", {
      method: 'GET',
      headers: myHeaders
 })
 .then(response => console.log(response)).catch(err=>console.log(err));

and

 fetch("http://192.168.1.71:3000/",{
   "method": "POST",
   headers: {
    'cache-control': 'no-cache',
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=utf-8',
 }, cache: "no-cache",})
.then(response => console.log(response))
.catch(err=>console.log(err));

but every time request.headers in server show this:

{ accept: 'application/json',
  'content-type': 'application/json; charset=utf-8',
  host: '192.168.1.71:3000',
  connection: 'Keep-Alive',
  'accept-encoding': 'gzip',
  'user-agent': 'okhttp/3.12.1' }

No cache-control come to server-side. Am i doing something wrong?

React Native adb reverse error: more than one device

$
0
0

I am learning react native. I can successfully connect my android device using USB. But when I try to connect it using wifi, it gives me an error.

$ adb kill-server      
$ adb version
Android Debug Bridge version 1.0.40
Version 4986621
Installed as /home/subtleseeker/Android/Sdk/platform-tools/adb          
$ adb connect 172.26.40.211:8081

* daemon not running. starting it now on port 5037 *
* daemon started successfully *
connected to 172.26.40.211:8081
$ adb devices                   
List of devices attached
172.26.40.211:8081      device

$ react-native run-android
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug)...
Starting a Gradle Daemon, 1 incompatible and 1 stopped Daemons could not be reused, use --status for details
cache results.bin (/home/subtleseeker/.gradle/caches/transforms-1/metadata-1.1/results.bin) is corrupt. Discarding.

> Task :app:installDebug 
Installing APK 'app-debug.apk' on 'POCO F1 - 8.1.0' for app:debug
Installed on 1 device.

BUILD SUCCESSFUL in 31s
27 actionable tasks: 1 executed, 26 up-to-date
Running /home/subtleseeker/Android/Sdk/platform-tools/adb -s 172.26.40.211:8081 reverse tcp:8081 tcp:8081
error: more than one device/emulator
Could not run adb reverse: Command failed: /home/subtleseeker/Android/Sdk/platform-tools/adb -s 172.26.40.211:8081 reverse tcp:8081 tcp:8081
Starting the app on 172.26.40.211:8081 (/home/subtleseeker/Android/Sdk/platform-tools/adb -s 172.26.40.211:8081 shell am start -n com.awe4/com.awe4.MainActivity)...
Starting: Intent { cmp=com.awe4/.MainActivity }

In the Dev settings of the app, I have configured Debug server host & port for device to the ip address of my computer as 172.26.43.71:8081. Also it is clear from the output, that the connection was successful and the apk is installed.

I can't see how to resolve this error: error: more than one device/emulator. Any help is appreciated.
NOTE: This question may be a duplicate of this, but it doesn't have any answers.

Can't find variable: Expo

$
0
0

I am making a app with react native. It has login with facebook option, it Keep gives me this error. "Facebook Login Error: Can't find variable: Expo" What am I doing wrong here?

Do I have to install some dependencies on linux

f.auth().onAuthStateChanged(function(user) {
  if(user){
    //logged in
    console.log('Logged in', user);
  }else {
    //logged out
    console.log('logged out');
  }
});



const { type, token} = await Expo.Facebook.logInWithReadPermissionsAsync(
  '529007557646715',
  { permissions: ['email', 'public_profile'] }
);

if(type === 'success'){
  const credential = firebase.auth.FacebookAuthProvider.credential(token);
    firebase.auth().signInWithCredential(credential).catch((error) => {
    console.log('Error...',error);
  })
}

Possible Unhandled Promise Rejection (id:0): ReferenceError: Can't find variable: Expo loginWithFacebook$

How To Fix memory leak in in Reaact Native?

$
0
0

I have a problem with my application that is a memory leak, where when the application that I developed during the debugger hangs.

I have unmounted state and event

Following a warning in debugger mode:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    in PTRViewAndroid (at Home.js:187)

React-Native Face detect from list of images

$
0
0

i want to detect faces from list of images which are listed from photo albums..

here is my code..

  // get All images from particular album

    await CameraRoll.getPhotos({
          first: count,
          after,
          assetType: 'Photos',
          groupTypes: 'All',
          groupName: this.props.navigation.state.params.album,
        })
          .then(r => {
            this.setState({ data: r.edges, isLoading: false, });

            this.state.data.map((p, index) => {
              this.getFaces(p.node.image.uri);
            });
          })
}

// Detect faces from list of images

async getFaces(uri) {
    await FaceDetector.detectFacesAsync(uri).then(res => {
      if (res.faces.length > 0) {
        console.log('Has faces: ' + uri);
        this.state.faceImage.push(uri);  // array of face images and set it to Flatlist
      } else {
        console.log('No faces: ' + uri);
      }
    });

      this.setState({
        faceImage: this.state.faceImage,
        isLoading: false,
      });

  }

All things are worked correctly but when image array size was big then my app was stuck and close only in android device.

React Native WebView html not opening options on Android tablets

$
0
0

I am experiencing a very strange problem in React Native's WebView with HTML <select> tags on Android tablets.

For some reason, tapping on the rendered <select> button does not open the options list.

This only happens on Android tablets, irrespective of the Android version. On Android smartphones, however, this bug does not occur and the options list opens as expected.

To reproduce this bug, I created a simple demo app: https://github.com/huonderv/react-native-webview-html-select-bug.

The important code is the following:

index.android.js

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

export default class WebViewProject extends Component {
  render() {
    return (
      <WebView
        style={styles.container}
        source={{ uri: 'file:///android_asset/simpleselect.html'}}
        startInLoadingState={true}
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

AppRegistry.registerComponent('WebViewProject', () => WebViewProject);

simpleselect.html

<!DOCTYPE html>
<html>
  <body>    
    <select>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="opel">Opel</option>
      <option value="audi">Audi</option>
    </select>

  </body>
</html>

I also tried to replace the WebView with Crosswalk, as described here: https://github.com/grovertb/react-native-crosswalk-webview. However, this did not solve this problem.

Does anyone know how to get this to work in React Native WebView on Android tablets?

I uploaded apk to play store using fastlane supply however cant find apk in the list of available apks

$
0
0

I am using Fastlane supply. After uploading apk to playstore I have notification that your update is live, and there is a date of creation of that notification. However, when I go to alpha test and press button add from library I don't see my apk in the list of apks. Is it permission problem, I have admin permission but I didn't create this account.


How should I fix "Content is not allowed in prolog" React-Native error?

$
0
0

I am facing an embarrassing error on my react-native project.
I tried to remove the content in string.xml file but I still get the following error:

Execution failed for task ':app:mergeDebugResources'.  
E:\New folder\jeeps\android\app\src\main\res\values\strings.xml:1:1: 
    Error: Content is not allowed in prolog.

ADB can't connect to Nox

$
0
0

i have a problem which i trying to solve for about 3 days and i can't find any working solution. The problem is i can't connect my nox player to adb when i trying to connect with localhost and port 62001. Everything i did is:

-nox_adb.exe

nox_adb.exe connect 127.0.0.1:62001 -> unable to connect to 127.0.0.1:62001.

nox_adb.exe connect 127.0.0.1:5037 -> connected to 127.0.0.1:5037 (but when i trying to run react native project with this deviceId, it returns "No Android devices connected")

-adb.exe (from Android SDK)

adb.exe connect 127.0.0.1:62001 -> unable to connect to 127.0.0.1:62001.

adb.exe connect 127.0.0.1:5037 -> failed to connect to 127.0.0.1:5037.

I have installed whole android studio with (i think) needed libraries, Google USB Driver, sdk platforms, etc. Platform: Windows 7 x64 Nox: 6.2.0.0

i have read:

Could someone tell me what I'm doing wrong?

How to generate APK file by Expo's Bare workflow but using previous expo's Managed workflow JKS file

$
0
0

I have Project which is previously running great on Expo. But due to native Utube experience i have to eject. Now i am in bare workflow and my problem is how to generate APK using the same jks file, keyAlias etc.

React Native: Packae com.reactnativenavigation.react doesn't exist

$
0
0

I am new to react native and trying to install react navigation library using the instruction give here https://wix.github.io/react-native-navigation/#/docs/Installing?id=android. after completing the final steps when i am doing react-native run-android that time i am getting below error.can someone help me in resolving below error. i am stuck with this issue from last two days

Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainActivity.java:3: error: package com.reactnativenavigation does not exist
import com.reactnativenavigation.NavigationActivity;
                                ^
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainActivity.java:5: error: cannot find symbol
public class MainActivity extends NavigationActivity {
                                  ^
  symbol: class NavigationActivity
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:13: error: package com.reactnativenavigation does not exist
import com.reactnativenavigation.NavigationApplication;
                                ^
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:14: error: package com.reactnativenavigation.react does not exist
import com.reactnativenavigation.react.NavigationReactNativeHost;
                                      ^
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:15: error: package com.reactnativenavigation.react does not exist
import com.reactnativenavigation.react.ReactGateway;
                                      ^
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:19: error: cannot find symbol
public class MainApplication extends NavigationApplication {
                                     ^
  symbol: class NavigationApplication
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:21: error: cannot find symbol
    protected ReactGateway createReactGateway() {
              ^
  symbol:   class ReactGateway
  location: class MainApplication
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:20: error: method does not override or implement a method from a supertype
    @Override
    ^
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:22: error: cannot find symbol
        ReactNativeHost host = new NavigationReactNativeHost(this, isDebug(), createAdditionalReactPackages()) {
                                   ^
  symbol:   class NavigationReactNativeHost
  location: class MainApplication
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:23: error: method does not override or implement a method from a supertype
            @Override
            ^
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:28: error: cannot find symbol
        return new ReactGateway(this, isDebug(), host);
                   ^
  symbol:   class ReactGateway
  location: class MainApplication
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:31: error: method does not override or implement a method from a supertype
    @Override
    ^
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:39: error: cannot find symbol
        return Arrays.<ReactPackage>asList(
               ^
  symbol:   variable Arrays
  location: class MainApplication
/home/sanjay/Desktop/ToDo/android/app/src/main/java/com/todo/MainApplication.java:44: error: method does not override or implement a method from a supertype
    @Override
    ^
14 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.

Below is my setting.graddle file

rootProject.name = 'ToDo'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
include ':react-native-navigation'
project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/lib/android/app/')

build.graddle

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

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 19
        compileSdkVersion = 28
        targetSdkVersion = 28
        //googlePlayServicesVersion   = "12.0.1"
        supportLibVersion = "28.0.3"
    }
    repositories {
        google()
        mavenLocal()
        mavenCentral()
        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 {
        google()
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }

        maven { url 'https://jitpack.io' }
    }
}

subprojects { subproject ->
    afterEvaluate {
        if ((subproject.plugins.hasPlugin('android') || subproject.plugins.hasPlugin('android-library'))) {
            android {
                variantFilter { variant ->
                    def names = variant.flavors*.name
                    if (names.contains("reactNative51") || names.contains("reactNative55") || names.contains("reactNative56") || names.contains("reactNative57") || names.contains("reactNative57_5")) {
                       setIgnore(true)
                    }
                }
            }
        }
    }
}

app/build.graddle

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.todo"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        missingDimensionStrategy "RNN.reactNativeVersion", "reactNative60" // See note below!
        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
            }

        }
    }
}

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support'&& requested.name != 'multidex') {
            details.useVersion "${rootProject.ext.supportLibVersion}"
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation project(':react-native-navigation')
    implementation 'com.android.support:design:25.4.0'
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    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)

React Native: Build Missing iOS + Android folders

$
0
0

I recently update my React Native + React dependencies. I then removed by iOS + android folders to create fresh ones, but the following command that used to work in the past is now giving an error

Dependencies:

  • React (16.11.0)
  • React Native (0.61.2)

What worked in the past:

react-native upgrade --legacy true

Error:

error: unknown option `--legacy'

What I've tried

  • I've even tried using just one dash too with -legacy
  • react-native upgrade (Doesn't work since I'm on the latest version of React Native)
Viewing all 29700 articles
Browse latest View live


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