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

react native project doesn't sync on emulating platform after saving files

$
0
0

I have joined a React Native project recently, and have just installed everything to make compiling and testing possible. But I have one problem that my colleague‏‏‏‏s don't have - when I try to save my code changes, what I worked on doesn't appear to have changed on the emulated platform (Genymotion), and only after I re-run

yarn android

the code syncs on the platform.

Any reason as to why that happens and how that can be fixed?


React Native TextInput Comp. Doesn't Work on Specific location in Android

$
0
0

EDITED. So, guys, you told me just write one question at a time. Now I fixed my little bugs but still, I have a bug that's so weird.

Now, I can't click on TextInput comp. in android below a specific location on the screen. To be clear;

when the styling is like that: -WORKS

input: {
    position: 'absolute', // probably it's about position, but I'm not sure
    top: 29, // I mean when top style prop is smaller than 30 it works
    width: '92%',
    height: 30,
    fontSize: 25,
    fontWeight: 'bold',
    color: '#000000',
    borderWidth: 1,
    borderColor: '#000000',
    borderRadius: 0,
    backgroundColor: '#fff',
    textAlign: 'left',
  }

However when it's like this: -DOESN'T WORK

input: {
    position: 'absolute',
    top: 30, // or 35 or 40
    width: '92%',
    height: 30,
    fontSize: 25,
    fontWeight: 'bold',
    color: '#000000',
    borderWidth: 1,
    borderColor: '#000000',
    borderRadius: 0,
    backgroundColor: '#fff',
    textAlign: 'left',
  }

And, I don't think it's necessary but this is the TextInput comp:

<View style={styles.inputContainer}>
    <TextInput
    style={styles.input}
    onChangeText={(text) => this.setState({input: text.toLowerCase()})}
    value={this.state.input}
    />
    <TouchableHighlight style={styles.sendButton} onPress={()=> this.handleSubmit()}>
      <View>
        <Icon name="send" color="#fff" size={30}/>
      </View>
      </TouchableHighlight>
  </View>

So, if you guys have any clue that you think it will be helpful, I'm listening with four ears :) Thanks in advance! Sorry for late edit :(

React native: how to get file size, mime type and extension?

$
0
0

I know react-native-fs and react-native-fetch-blob, but I'm missing simple helper functions like getFileInfo(file).

Desired pseudo code:

let fileInfo = getFileInfo('path/to/my/file.txt');
console.log('file size: ' + fileInfo.size);
console.log('mime type: ' + fileInfo.type);
console.log('extension: ' + fileInfo.extension);

What's the proper way to get the file size, mime type and extension?

Thanks in advance!

Recommended .gitignore for react-native

$
0
0

I'm trying out react native and ejected into a full build environment. Sadly, the eject-script did not create a sensible .gitignore file.

Not knowing a lot about app-development, I wonder what directories I could .gitignore here?

I'm guessing:

  • android/build
  • android/app/build
  • android/.gradle/

Are these alright, or are there any more directories I should .gitignore?

React Native app crash on start - Android

$
0
0

enter image description hereI have a live react native app which was working fine before I integrate firebase cloud messaging. After integration it started crashing app. After that I removed all firebase integration from app and it still kept on crashing everytime I run app on my Android device. It always crash on start on both debug as well as release version of the app.

Here is the logcat:

2019-11-27 18:16:25.292 24260-24280/? E/ReactNativeJS: TypeError: undefined is not an object (evaluating 'new f.ListView.DataSource')
2019-11-27 18:16:25.297 24260-24280/? E/ReactNativeJS: Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

    --------- beginning of crash
2019-11-27 18:16:25.299 24260-24281/? E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
    Process: com.telehealthcare, PID: 24260
    com.facebook.react.common.JavascriptException: TypeError: undefined is not an object (evaluating 'new f.ListView.DataSource'), stack:
    <unknown>@881:701
    v@2:1474
    <unknown>@6:347
    v@2:1474
    d@2:876
    global code@1026:4

        at com.facebook.react.modules.core.ExceptionsManagerModule.reportException(ExceptionsManagerModule.java:71)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:371)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:150)
        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:26)
        at android.os.Looper.loop(Looper.java:164)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:225)
        at java.lang.Thread.run(Thread.java:764)

Project Level build file:

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

buildscript {
    ext {
        buildToolsVersion = "29.0.0"
        minSdkVersion = 21
        compileSdkVersion = 29
        targetSdkVersion = 29
        supportLibVersion = "27.1.1"
    }
    repositories {
        google()
        jcenter()
        maven { // <---- Add this block
            url "https://github.com/jitsi/jitsi-maven-repository/raw/master/releases"
        }
    }
    dependencies {
//        classpath 'com.android.tools.build:gradle:3.1.4'
        classpath 'com.android.tools.build:gradle:3.3.0'
        classpath 'com.google.gms:google-services:4.3.2'

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

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven { // <---- Add this block
            url "https://github.com/jitsi/jitsi-maven-repository/raw/master/releases"
        }
    }
}


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

App Level build.gradle:

apply plugin: "com.android.application"
//apply plugin: 'com.google.gms.google-services'
//com.google.gms.googleservices.GoogleServicesPlugin
import com.android.build.OutputFile

project.ext.react = [
    entryFile: "index.js",
    enableHermes: false,
//    bundleAssetName: "app.bundle",
]

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

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+'

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

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion '29.0.0'

    defaultConfig {
        applicationId "com.telehealcare"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 9
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
//        ndk {
//            abiFilters "armeabi-v7a", "x86"
//        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
//            include "armeabi-v7a", "x86"
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }

    buildTypes {
        debug {
            debuggable true
        }
        release {
            multiDexKeepFile file('multidex-config.txt')
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
//            def versionCodes = ["armeabi-v7a":1, "x86":2]
            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
            }
        }
    }

    packagingOptions {
        pickFirst '**/armeabi-v7a/libc++_shared.so'
        pickFirst '**/x86/libc++_shared.so'
        pickFirst '**/arm64-v8a/libc++_shared.so'
        pickFirst '**/x86_64/libc++_shared.so'
        pickFirst '**/x86/libjsc.so'
        pickFirst '**/armeabi-v7a/libjsc.so'
    }
}


dependencies {
    implementation project(':react-native-cardview')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'com.facebook.fresco:animated-gif:1.10.0'
    implementation project(':react-native-contacts')
    implementation(project(':react-native-jitsi-meet'))

    // Jitsi Meet
    implementation ('org.jitsi.react:jitsi-meet-sdk:2.+') { transitive = true }


    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha03'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.android.support:multidex:1.0.3'


    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
//    implementation "com.google.android.gms:play-services-base:15.0.1"
//    implementation "com.google.firebase:firebase-core:15.0.0"
//    implementation "com.google.firebase:firebase-auth:17.0.0"
//    implementation 'com.google.firebase:firebase-messaging:20.0.0'

//     Glide
//    implementation("com.github.bumptech.glide:glide:4.7.1") {
//        exclude group: "com.android.support", module: "glide"
//    }
//    implementation("com.github.bumptech.glide:annotations:4.7.1") {
//        exclude group: "com.android.support", module: "annotations"
//    }
}

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

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == "androidx") {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion "${targetSdk}.+"
            }
        }
    }
}
//apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

package.json file:

{
  "name": "TeleHealCare",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "android": "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 && react-native run-android",
    "ios": "react-native run-ios"
  },
  "dependencies": {
    "moment": "^2.24.0",
    "react": "16.6.3",
    "react-moment": "^0.9.2",
    "react-native": "^0.61.4",
    "react-native-animatable": "^1.3.0",
    "react-native-calendars": "^1.21.0",
    "react-native-card-stack-swiper": "^1.1.0",
    "react-native-cardview": "^2.0.2",
    "react-native-circular-action-menu": "^0.5.0",
    "react-native-contacts": "^2.2.4",
    "react-native-datepicker-dialog": "0.0.9",
    "react-native-elements": "^1.0.0-beta7",
    "react-native-expandable-section-list": "^1.0.7",
    "react-native-jitsi-meet": "^1.2.0",
    "react-native-loader": "^1.2.1",
    "react-native-material-dropdown": "^0.11.1",
    "react-native-material-textfield": "^0.12.0",
    "react-native-modal-datetime-picker": "^6.0.0",
    "react-native-parallax-scroll-view": "^0.21.3",
    "react-native-swipeout": "^2.3.6",
    "react-native-switch": "^1.5.0",
    "react-native-tab-view": "^1.3.1",
    "react-native-table-component": "^1.2.0",
    "react-native-vector-icons": "^6.4.2",
    "react-navigation": "^2.18.2",
    "toggle-switch-react-native": "^2.0.2",
    "url-search-params": "^1.1.0"
  },
  "devDependencies": {
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.51.1",
    "react-test-renderer": "16.6.3"
  },
  "jest": {
    "preset": "react-native"
  }
}

MainApplication.java:

public class MainApplication extends MultiDexApplication implements ReactApplication {

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {

            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
                    new JitsiMeetPackage(),
                    new RNCardViewPackage(),
                    new ReactNativeContacts()
            );
        }

        @Override
        protected String getJSMainModuleName() {
            return "index";
        }

    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
    }
}

MainActivity.java:

public class MainActivity extends ReactActivity {
    private static MainActivity mainActivity;

    @Override
    protected String getMainComponentName() {
        return "TeleHealCare";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = this;
    }

    public static void callJitsi(){
        mainActivity.startActivity(new Intent(mainActivity,JitsiActivity.class));
    }
}

Please do let me know what is going wrong here. Any help will be appreciate!

Deeplink: go-back to browser from myApp, after clicking back-button in android, react-native

$
0
0

I am using Android app, which is openned from chrome using Deeplink,

1) Code of AndroidManifest.xml file, which opens myApp(React-Native) when I click deeplink in browser.

<intent-filter android:label="@string/app_name">
        <data android:scheme="myapp"
              android:host="myhost" 
              />
        </intent-filter>

2) url-link of browser, which opens app, by matching scheme://host, and I am passing URL's too, as:

Open myApp

3) I am using React-native, for getting those params as:

Linking.getInitialURL().then((url) => {
      if (url) {
        this.setState({
          'opened_from_url': true,
          'open_url': url
        })
      }
      else
        this.setState({
          'opened_from_url': false
        })

4) to goback to same page, from where I came in app is done as:

Linking.openURL(url).catch((err) => console.error('An error occurred', err));

But this opens app, in chrome/otherBrowsers as new-page, not same one,

5) How can come-back to same page, from where I came to app, without going in new-tab, implementing in core-java(AndroidManifest.xml) or react-native would be ok.

react-native run-android build successful but Does not work with Access Denied

$
0
0

I'm a developer developing react-native using VSC on Windows. The build succeeds, but it turns out not to run

The react-native run-android command printed BUILD SUCCESSFUL.

But unfortunately in the next line Access is denied. enter image description here With only a message, the app is installed on the device, but it doesn't run. When I run it, I see the make sure blabla error screen that appears when there is no node server.

This problem eliminated my two days. I want to get help.

Ps. Note that project asd is a new project for testing. If you look at the existing project and test project, I guess it might be Java configuration, but ... I am suffering because there is no proper solution.

Error: Actions may not have an undefined "type" property. Have you misspelled a constant?

$
0
0

I cannot for the life of me figure out what I did wrong. I checked out other peoples post that are similar to mine and cant find whats wrong, can somebody help? I only started react and functional programming yesterday so a lot of this stuff is new to me. As far as I know, something must be wrong with my actions or how I defined my types correct? Here is my code.

index.android.js

function configureStore(initialState) {
    const enhancer = compose(
        applyMiddleware(
            thunkMiddleWare,
            loggerMiddleWare,
        ),
    );
    return createStore(reducer, initialState, enhancer)
}
const store = configureStore({});

const App = () => (
    <Provider store={store}>
        <AppContainer/>
    </Provider>
)

AppRegistry.registerComponent('BHPApp', () => App);

As well as my components, reducers, actions and types.

ACTIONS

import * as UserActions from './users'

export const ActionCreators = Object.assign({},
    UserActions
);

export const SET_ALL_USERS = 'SET_ALL_USERS';

import * as types from './types'
import ApiUtils from '../lib/apiUtils'

export function fetchAllUsers() {
    return (dispatch, getState) => {
        return fetch(URL + '/user/getAll')
            .then(ApiUtils.checkStatus)
            .then(response => {
                dispatch(setAllUsers({ hBaseUsers: response }));
            })
            .catch(e => {
                console.log(e)
            })
    }
}

function setAllUsers( {hBaseUsers} ) {
    hBaseUsers.forEach((hBaseUser) => {
        console.log(hBaseUser);
    });
    return {
        types: types.SET_ALL_USERS,
        hBaseUsers,
    }
}

REDUCERS

import { combineReducers } from 'redux'
import * as userReducer from './users'

export default combineReducers(Object.assign(
    userReducer,
));

import createReducer from '../lib/createReducer'
import * as types  from '../actions/types'

export const getUsers = createReducer({}, {
    [types.SET_ALL_USERS](state, action){
        let newState = {};
        action.hBaseUsers.forEach( (hBaseUser) => {
           newState[hBaseUser.personUniqueID] = hBaseUser;
        });
        return newState;
    }
});

export const userCount = createReducer({}, {
    [types.SET_ALL_USERS](state, action){
        action.hBaseUsers.length;
    }
});

CONTAINERS

class AppContainer extends Component{
    render(){
        return <Home {...this.props} />
    }
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators(ActionCreators, dispatch);
}

    export default connect((state) =>  { return {} }, mapDispatchToProps)(AppContainer);
import React, { Component } from 'react'
import { connect } from 'react-redux'
import {
    ScrollView,
    View,
    TextInput,
    Image,
    TouchableHighlight,
    StyleSheet,
    Text
} from 'react-native'

class Home extends Component{
    searchPressed(){
        this.props.fetchAllUsers();
    }

    hBaseUsers(){
        return Object.keys(this.props.getUsers).map( key =>  this.props.getUsers[key])
    }

    render(){
        console.log(this.hBaseUsers());
        return<View>
            <View>
                <TouchableHighlight onPress={() => this.searchPressed() } >
                    <Text>Fetch Users</Text>
                </TouchableHighlight>
            </View>
            <ScrollView>
                {this.hBaseUsers().map((hBaseUser) => {
                    return <View>
                        <Text>
                            hBaseUser.personUniqueID
                        </Text>
                    </View>
                })}
            </ScrollView>
        </View>
    }
}

function mapStateToProps(state) {
    return{
        getUsers: state.getUsers
    }
}

export default connect(mapStateToProps)(Home);

After everything I read, my issue can be in any of these things but I cant seem to find it. As far as i know, I spelled and defined everything correctly. Can somebody please help me?


Why BroadcastReceiver don't work in React Native?

$
0
0

I try to develop an application that in the future can run a service, the service I want to run when I connect to a network.

At the moment I only need the receiver to print in the log (using react-native log-android) that has been connected or disconnected, or to visualise a toast with a message, all this in the background not in the foreground.

Try the following,

First I put the receiver in the AndroidManifest.xml

<application>
  ...
  <receiver android:name="com.air_fighers_react_native.receiver.NetworkChangeReceiver">
    <intent-filter>
      <action android:name="android.net.conn.CONECTIVITY_CHANGE"/>
    </intent-filter>
  </receiver>
</application>

Even add the permissions:

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

Create the receiver folder in java > com > air_fighters_react_native > receiver and inside the NetworkChangeReceiver.java file with the following code:

package com.air_fighters_react_native.receiver;

import android.content.BroadcastReceiver
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class NetworkChangeReceiver extends BroadcastReceiver {
  public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Cambio de conexion.", Toast.LENGTH_LONG).show();
  }
}

With this it is supposed that it should be enough, however when running the application there are no problems, but when I close the application and activate and deactivate the WiFi the toast message is not displayed, not even when I have the application in the foreground.

I have already tried changing receiver to:

<receiver android:name=".NetworkChangeReceiver">

And changing NetworChangeReceiver to the same level as MainApplication and MainActivity in folders.

Java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/FirebaseApp

$
0
0

Screenshot from Android Studio

Google Play Services

This is React Native project. I have an error after successful build in Android Studio Emulator:

java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/FirebaseApp

My files:

package.json:

...
"react-native": "^0.55.3",
"react-native-camera": "1.1.2",
"react-native-check-box": "^2.1.0",
"react-native-extended-stylesheet": "^0.8.1",
"react-native-firebase": "^4.2.0",
"react-native-geocoder": "^0.5.0",
"react-native-git-upgrade": "^0.2.7",
"react-native-htmlview": "^0.12.1",
"react-native-image-picker": "^0.26.10",
"react-native-linear-gradient": "^2.4.0",
"react-native-local-storage": "^1.5.2",
"react-native-maps": "^0.21.0",
"react-native-modal": "^5.4.0",
"react-native-modal-dropdown": "^0.6.1",
"react-native-read-more-text": "^1.0.0",
"react-native-router-flux": "^4.0.0-beta.27",
"react-native-svg-image": "^2.0.1",
"react-native-text-input-mask": "^0.7.0",
...

android/app/build.gradle:

...    
android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"

    defaultConfig {
        applicationId "com.something.anything"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        multiDexEnabled true
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            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:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            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 {
    compile(project(':react-native-firebase')) {
        transitive = false
    }
    compile project(':react-native-geocoder')
    compile(project(':react-native-maps')) {
      exclude group: 'com.google.android.gms', module: 'play-services-base'
      exclude group: 'com.google.android.gms', module: 'play-services-maps'
      exclude group: 'com.google.android.gms', module: 'play-services-location'
    }

    compile 'com.google.android.gms:play-services-base:15.+'
    compile 'com.google.android.gms:play-services-maps:15.+'
    compile 'com.google.android.gms:play-services-location:15.+'
    compile (project(':react-native-camera')) {
    exclude group: "com.google.android.gms"
    compile 'com.android.support:exifinterface:25.+'
    compile ('com.google.android.gms:play-services-vision:12.0.1') {
        force = true
        }
    }
    compile project(':react-native-text-input-mask')
    compile project(':react-native-linear-gradient')
    compile project(':react-native-image-picker')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
}

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

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

android/build.gradle

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

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

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

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

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

I've tried a lot of solutions but nothing helped.

What is the best approach to passing data from a notification to the application that it opens, using "react-native-firebase v6"?

$
0
0

I want to implement opening a specific screen when interacting with a Push Notification sent from Firebase. My understanding is that I needed to use was getInitialNotification() function that was available in react-native-firebase v5 and lower, but is not available yet in react-native-firebase v6, since the Notifications package is not yet ready. Among other things, so far I have tried setting the background message handler that is available in the Cloud Messaging package, but it doesn't seem to work for something that is not a data-only message:

Firebase.messaging().setBackgroundMessageHandler(async (remoteMessage) => { await storeJSONData('notification', JSON.stringify(remoteMessage)); });

Should I downgrade to react-native-firebase v5 in order to use their getInitialNotification() from the Notifications package, or do I have other better alternatives, like even using android native code?

You attempted to use a fire base module that's not installed on your android project by calling firebase.analytics()

$
0
0

I have installed firebase into my react native app, I will need to firebase analytics module.

app/build.gradle:

    implementation 'com.google.firebase:firebase-core:17.2.1'
    implementation "com.google.android.gms:play-services-gcm:16.0.0"
    implementation "com.google.firebase:firebase-messaging:20.0.1"
    implementation "com.google.firebase:firebase-analytics:17.2.1"

MainActivity.java

private FirebaseAnalytics mFirebaseAnalytics;

@Override
protected void onCreate(Bundle savedInstanceState) {
    SplashScreen.show(this, R.style.SplashScreenTheme);  // here
    super.onCreate(savedInstanceState);

    // Obtain the FirebaseAnalytics instance.
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
}

react native

import firebase from "react-native-firebase";
firebase.analytics().logEvent("your_custom_event", {"custom_parm": "cp_value"});

but I get this error on logcat console on android studio:

E/ReactNativeJS: Error: You attempted to use a firebase module that's not installed on your Android project by calling firebase.analytics().

Ensure you have:

1) Installed the required Firebase Android SDK dependency 'com.google.firebase:firebase-analytics' in your 'android/app/build.gradle' file.

2) Imported the 'io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage' module in your 'MainApplication.java' file.

3) Added the 'new RNFirebaseAnalyticsPackage()' line inside of the RN 'getPackages()' method list.

See http://invertase.link/android for full setup instructions.

and in react native console I see:

D8: Program type already present: android.support.v4.app.INotificationSideChannel$Stub$Proxy

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

$
0
0

I've followed step by step the official Getting Started. I started from a clean linux install and installed everything required as per the "Building Projects with Native Code" tab. I have also read the troubleshooting section. I've already created the project using the terminal.

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

    Starting JS server...
    Building and installing the app on the device (cd android && ./gradlew installDebug)...

    ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

    Please set the JAVA_HOME variable in your environment to match the
    location of your Java installation.

    Could not install the app on the device, read the error above for details.
    Make sure you have an Android emulator running or a device connected and have
    set up your Android development environment:
    https://facebook.github.io/react-native/docs/android-setup.html

It does not find JAVA_HOME because the latest versions of Android Studio don't require Java to be installed in the system. Instead an internal JRE is used.

Duplicate disclaimer: I've already read this question. This is not what I want. I know how to set the Java home. I just want to run the react project WITHOUT having to install a separate Java.

Questions:

  1. How could I find the internal Java inside the Android Studio folder so that I could point JAVA_HOME to it?
  2. If not possible, could I open and run the project inside the android folder with Android Studio? How would I refresh this project after modifying the React JavaScript code in the parent folder?

react-native run-android Building Error ':app:generateDebugBuildConfig'

$
0
0

I am having a problem to build a new project. I am using React-Native and Android Emulator (AVD) but when I use the command react-native run-android I get the following message:

FAILURE: Build failed with an exception.

* What went wrong:

Execution failed for task ':app:generateDebugBuildConfig'.

> java.io.IOException: Could not delete path 'C:\Users\diego\Desktop\Diego\albums\android\app\build\generated\source\buildConfig\debug\com'.

* Try:

Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 2 mins 47.189 secs

Could not install the app on the device, read the error above for details. Make sure you have an Android emulator running or a device connected and have set up your Android development environment: https://facebook.github.io/react-native/docs/android-setup.html

Here's an image of the prompt: Image of the problem

How can I fix this?

-------------------------------------------------------------UPDATE-------------------------------------------------------

I added the value C:\....\AppData\Local\Android\sdk\tools to the variable Path and I got build sucessful. Problem solved. Yay.

Thanks.

How do you run react-native app in production mode?

$
0
0

I thought you could do this with react-native run-android --dev=false, but doing this doesn't stop the developer menu from showing up when I shake the phone and the request url to the packager has dev=true in the url params.


production config for android manifestPlaceholders

$
0
0

I am using react native, have a service inject config build.gradle file:

   manifestPlaceholders = [
        APPKEY: "xx",
        CHANNEL: "xxx"
    ]

I am planing to have two configs, one is for dev and another or production.

How to do it?

react-native: command not found

$
0
0

I am getting -bash: react-native: command not found error while creating react-native project.

Below are the additional info

1. brew --version
   homebrew 0.9.9
2  brew info watchman
   watchman `enter code here`stable 4.50
   /usr/local/Cellar/watchman/4.4.0
3. brew info flow
   stable 0.24.1
   /usr/local/Cellar/flow/0.24.1
4. brew info node
   stable 6.1.0
   /usr/local/Cellar/node/6.1.0
5. npm -version
   3.8.6
6. echo $PATH
/Users/Ashok/.rbenv/shims:/Users/Ashok/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

I tried suggested steps from the below link but still i am getting same error.

  1. react-native-command-not-found

I don't have any "npm" directory which they have specified in the solution

Ashoks-MacBook-Pro:share Ashok$ ls
aclocal     doc     info        ruby-build  zsh
autoconf    emacs       man     systemtap

But i found npm file exist in below location.

/usr/local/Cellar/node/6.1.0/etc/bash_completion.d

I uninstalled react-native and installed again but still i am facing same issue.

React-native componentWillUnmount not being called

$
0
0

I'm running on Android and if I used the hardware back button to exit the application the componentWillUnmount function gets called. However, if I use the square button to show the list of running apps and swipe to close the function does not get called.

Any ideas on how to detect when the app is being closed so that I can clear timers, save data etc.

Thanks.

React Native: Failed to notify project evaluation listener. > JAVA_LETTER_OR_DIGIT

$
0
0

I'm getting error when i try to run android code in react native using react-native run-android.

I am running code on ubuntu.

 rahul@rahul-Inspiron-15-3567  ~/Documents/reactNative/crowdalert/CrowdAlert-Mobile   master ●  react-native run-android 
Scanning folders for symlinks in /home/rahul/Documents/reactNative/crowdalert/CrowdAlert-Mobile/node_modules (8ms)
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug)...

> Configure project :app 
WARNING: The option 'android.enableAapt2' is deprecated and should not be used anymore.
Use 'android.enableAapt2=true' to remove this warning.
It will be removed at the end of 2018..
Reading env from: .env
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html


FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Failed to notify project evaluation listener.
   > JAVA_LETTER_OR_DIGIT

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

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

Android studio is showing error in app level build.gradle file but it is not showing the line number so i have pasted mine code for app level build.gradle file too.

running the app in react native too shows the same error

apply plugin: "com.android.application"
apply plugin: "io.fabric"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

import com.android.build.OutputFile

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

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

android {
    // because of firestore:
    dexOptions {
        javaMaxHeapSize "4g"
    }
    compileSdkVersion 27

    defaultConfig {
        applicationId "com.crowdalert"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        // because of firestore:
        multiDexEnabled true
    }
    signingConfigs {
       release {
           if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
               storeFile file(MYAPP_RELEASE_STORE_FILE)
               storePassword MYAPP_RELEASE_STORE_PASSWORD
               keyAlias MYAPP_RELEASE_KEY_ALIAS
               keyPassword MYAPP_RELEASE_KEY_PASSWORD
           }
       }
   }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
        debug {
            minifyEnabled false
            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:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            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 {
    compile 'com.facebook.fresco:animated-base-support:1.3.0'
    compile 'com.facebook.fresco:animated-gif:1.3.0'
    compile project(':react-native-vector-icons')
    compile(project(':react-native-firebase')) {
        transitive = false
    }
    compile project(':react-native-fetch-blob')
    compile project(':react-native-push-notification')
    compile project(':react-native-image-picker')
    compile project(':react-native-config')
    compile project(':react-native-android-location-services-dialog-box')
    compile(project(':react-native-maps')){
      exclude group: 'com.google.android.gms', module: 'play-services-base'
      exclude group: 'com.google.android.gms', module: 'play-services-maps'
  }
  compile 'com.google.android.gms:play-services-maps:15.0.0'
    compile project(':react-native-google-signin')
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile project(':react-native-fbsdk')
    implementation(project(':react-native-firebase')) {
        transitive = false
    }
    compile "com.google.android.gms:play-services-auth:15.0.0"
    // RNFirebase required dependencies
    implementation "com.google.firebase:firebase-core:15.0.2"
    implementation "com.google.android.gms:play-services-base:15.0.0"

    // RNFirebase optional dependencies
    implementation "com.google.firebase:firebase-ads:15.0.0"
    implementation "com.google.firebase:firebase-auth:15.1.0"
    implementation "com.google.firebase:firebase-config:15.0.0"
    implementation "com.google.firebase:firebase-database:15.0.0"
    implementation "com.google.firebase:firebase-invites:15.0.1"
    implementation "com.google.firebase:firebase-firestore:16.0.0"
    implementation "com.google.firebase:firebase-messaging:15.0.2"
    implementation "com.google.firebase:firebase-perf:15.1.0"
    implementation "com.google.firebase:firebase-storage:15.0.2"
    implementation 'com.google.firebase:firebase-analytics:17.2.0'

    implementation('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') {
        transitive = true
    }

    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'com.facebook.android:facebook-android-sdk:[5,6)'
    implementation "com.android.support:appcompat-v7:27.0.2"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

// 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 plugin: 'com.google.gms.google-services'

React-native formik form refs are always null

$
0
0

I have a component with an TextInput & Text :

const InputWithMessage = ({ label, formikProps, formikKey,ref, ...rest }) => {
  if (formikProps.touched[formikKey] && formikProps.errors[formikKey]) {
    styles.inputStyles.borderColor = 'red';
  }
  return (
    <View style={styles.inputStyles}>
      <TextField
        lineWidth={0}
        activeLineWidth={0}
        style={styles.textFieldStyles}
        label={label}
        ref={ref}
        tintColor={
          formikProps.touched[formikKey] && formikProps.errors[formikKey]
            ? colors.red
            : colors.primary
        }
        onChangeText={e => formikProps.setFieldValue(formikKey, e)}
        onBlur={formikProps.handleBlur(formikKey)}
        {...rest}
      /> .....  

This component is used in a formik form with refs to go from one input to another :

<View style={{width: '50%',marginRight: 1}}>
                    <InputWithMessage
                      formikProps={formikProps}
                      formikKey="firstName"
                      value={formikProps.values.firstName}
                      placeholder="Prénom*"
                      returnKeyType="next"
                      ref={this.firstName}
                      onSubmitEditing={() => {
                         this.birthName.current.focus()
                       }}
                      blurOnSubmit={false}
                      keyboardType='default'
                      autoFocus
                    /> ....  

I shove my refs like this in the constructor: this.birthName = React.createRef();

Except that my dreams are all the time null and so the focus can not be done...

any ideas?

Viewing all 28476 articles
Browse latest View live


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