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

React Native (Android Native Module): Get access to ReactContext in another Class?

$
0
0

I want to call a method in MyCustomModuleClass extends ReactContextBaseJavaModule from another Class

MyCustomModule.java

public class MyCustomModule extends ReactContextBaseJavaModule {

  private ReactContext mReactContext;

  public MyCustomModule(ReactApplicationContext reactContext) {
    super(reactContext);
    mReactContext = reactContext;
  }

  @Override
  public String getName() {
    return "CustomModule";
  }


    private void sendEvent(String eventName, Object params) {
        mReactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, params);
    }    
}

I'm trying this..

OtherClass.java

public class OtherClass extends AnotherClass {

    @Override
    protected void eventOccurred(Context context) {
        MyCustomModule RNC = new MyCustomModule(?);//-> Can't call without ReactContext
        RNC.sendEvent("CustomEvent", ObjectData); 
    }   
}

Sorry, I know nothing about java, could any one please help me out?

Is there any way I can get ReactContext in OtherClass?


How I get state from reducer in action for get name using redux

$
0
0

Here is my code below:

`action.JS`

export const stockList = (id) => (dispatch) => {

    dispatch({ type: STOCK_LIST });

    // alert('api called')
    callApiStockList(dispatch)
};

const callApiStockList = (dispatch) => {
    const URL = 'http://dashboardstaging.africanmanagers.org:8084/api/v1/stocks/10'
    fetch(URL, {
        method: 'GET',
        headers: '',
    })
        .then(response => response.json())
        .then(responseJson => {

            if (responseJson.data !== undefined) {

                const obj = {               
               data: responseJson.data
                }

                getStockListSuccess(dispatch ,obj);

              } 
              else 
              {
                // alert('failed')
                getStockListFail(dispatch, 'get stock list failed');
              }  
          })
        .catch(error => {
            console.log('ERROR:', error);
            getStockListFail(dispatch, "stock list failed");
        });
};

`reducer.JS`

import {
    CATEGORY_LIST_SUCCESS,
    CATEGORY_LIST_FAIL,
    CATEGORY_LIST

} from '../actions/types';

const INITIAL_STATE = {
    categorylistData:[],
    loading: false,
    error: ''
};

export default (state = INITIAL_STATE, action) => {

    switch (action.type) {

        case CATEGORY_LIST:
            return { ...state, loading: true, error: '' }

        case CATEGORY_LIST_SUCCESS:
            return { ...state, loading:false, error: '', categorylistData:action.payload.data }

        case CATEGORY_LIST_FAIL:
            return { ...state, loading:false, categorylistData :[] }

        default:
            return state;
    }
}

i get updated categorylistData in action file's callApiStockList function where i get obj in response of api.i want to compare categoryID's of categorylistdata and responseJson.data for getName of category from categorylistData.I tried with getState method but not working.Please anyone can help me.

How to create a React Native package which has an Android Library module?

$
0
0

I want to create a React Native package with native modules in it. The Android part also should have a Android Library module added to it. How do I do this?

I have tried adding in the dependencies block of build.gradle of the package.

implementation project(path: ':lib2')

But I get the error:

ERROR: Project with path ':lib2' could not be found in project ':react-native-mod'.

React Native Android build failed after upgrading 0.51 to 0.64

$
0
0

I have updated my react-native project from 0.51.0 to the latest version. After updating everything clearly as mentioned in the documentation, I am getting below error when I try to run my app. I already clean gradlew and .gradle/caches several times

1- cd android && ./gradlew clean && cd .. && react-native run-android

Here is build.gradle file

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 20
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    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' }
    }
}

subprojects {
    afterEvaluate {project ->
        if (project.hasProperty("android")) {
            android {
                compileSdkVersion 28
                buildToolsVersion "28.0.3"
            }
        }
    }
}

I expect to run the android app clearly but It gives the below error. I tried invalidating caches/restart too. But that was not helped me.

What went wrong: Execution failed for task ':app:processDebugResources'. Android resource linking failed /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:11: AAPT: error: attribute layout_constraintBottom_toBottomOf (aka com.xxx.ppm:layout_constraintBottom_toBottomOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:11: AAPT: error: attribute layout_constraintStart_toStartOf (aka com.xxx.ppm:layout_constraintStart_toStartOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:11: AAPT: error: attribute layout_constraintTop_toTopOf (aka com.xxx.ppm:layout_constraintTop_toTopOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:23: AAPT: error: attribute layout_constraintEnd_toEndOf (aka com.xxx.ppm:layout_constraintEnd_toEndOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:23: AAPT: error: attribute layout_constraintStart_toEndOf (aka com.xxx.ppm:layout_constraintStart_toEndOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:23: AAPT: error: attribute layout_constraintTop_toTopOf (aka com.xxx.ppm:layout_constraintTop_toTopOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:45: AAPT: error: attribute layout_constraintBottom_toBottomOf (aka com.xxx.ppm:layout_constraintBottom_toBottomOf) not found. /Users/username/.gradle/caches/transforms-2/files-2.1/7f6257c2b8e43de19785244bfe890f9d/res/layout/dg_fragment_region_select.xml:45: AAPT: error: attribute layout_constraintTop_toBottomOf (aka com.xxx.ppm:layout_constraintTop_toBottomOf) not found. error: failed linking file resources.

React-native-gesture-handler swipeable is not working on Android

$
0
0

Here is my code.

App.js

import Swipeable from 'react-native-gesture-handler/Swipeable';

const RightActions = () => {
  return (
    <TouchableOpacity onPress={() => console.warn('works'))}>
      <Icon name="md-trash" size={18} color={Colors.red} />
    </TouchableOpacity>
  );
};

const App = () => {
  return (
    <ScrollView>
    ...
      {Object.keys(data).map(key => {
        return (
          <Swipeable key={key} renderRightActions={RightActions}>
            <View>
              <Text>Swipe left</Text>
            </View>
          </Swipeable>
        );
      });
    </ScrollView>
  );
};

export default App;

And here is my MainActivity.java as the package suggest.

package com.project;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "project";
    }

    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected ReactRootView createRootView() {
                return new RNGestureHandlerEnabledRootView(MainActivity.this);
            }
        };
    }
}

I don't understand what is going on but it's a bit frustrating. Is there anyone who knows what to do ? My code is an exact copy of a tutorial i found so i expected it to work. The only difference is that my project uses react-native while the tutorial used expo.

Not able to bundle application using react-native start

$
0
0

I was getting one error :

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

So I have fired this command :

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

So that error gone, but Now problem is I am not able to debugging. If I am using react-native start command then also in not bundling.

So main problem is I am not able to bundle application.

Please guide on this point.

Thanks.

Issue in AES encryption for android - dev vs release build using react-native-crypto-js package

$
0
0
import CryptoJS from "react-native-crypto-js";

//encryption function used in react native code base

export const encryptValue = (text) => {

try {

        const key = 'J4f9eO8ayjjEtamRBxSSmsDqXBele1zl'
        const iv = CryptoJS.lib.WordArray.random(128 / 8)
        let encrypted = CryptoJS.AES.encrypt(
            text, key, {
                keySize: 16,
                iv: iv,
            });
        let v = { iv: iv.toString(), encryptedData: encrypted.toString() }
        return v
    } catch (error) {
        console.log('error - ', error)
    }
}

const crypto = require('crypto-js')

//decryption function used in server - node

export const decrypt = (data) => {


try {

        let key = "J4f9eO8ayjjEtamRBxSSmsDqXBele1zl"
        let decrypted = crypto.AES.decrypt(
            data.encryptedData, key, {
                keySize: 16,
                iv: data.iv
            }).toString(crypto.enc.Utf8)
        console.log('decrypted - ', decrypted)
        return decrypted.toString()
    } catch (err) {
        console.log('err', err)
    }

}

Above code encryption and decryption works fine for android debug build and server side code. However, Android build generated in release.. generates encrypted text, but does not decrypt at server.

Fetch request displaying response on iOS but not working with android

$
0
0

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

Frontend

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


export default class App extends React.Component {

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

      data:''

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

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

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

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

  },

});

Backend

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

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





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

AndroidManifest.xml

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

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

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:usesCleartextTraffic="true"
      tools:targetApi="28"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
       <meta-data
     android:name="com.google.android.geo.API_KEY"
     android:value="AIzaSyD4Js3-PNHs1aL4XEmw6mAomblC2b4ys5s"/>
    </application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

React native async storage error: package com.facebook.react.module.annotations does not exist

$
0
0

Anyone familiar with this error when migrating over to Androidx ? The error points to the @react-native-community/async-storage.

error: package com.facebook.react.module.annotations does not exist

I'm running on react-native 0.60.5 and @react-native-community-async-storage 1.6.1

Below is the error message when I run ./gradlew build --stacktrace

expo keeps stopping android emulator

$
0
0

I am running an expo app on windows 10 using the android emulator. The tunnel builds, and the simulator starts. but expo keeps crashing on the simulator.

enter image description here

I tried uninstalling expo off the simulator, and rebooting the machine. Any ideas?

React Native Duplicate class com.google.android.gms.measurement.internal.zzhw

$
0
0

I just did few changes in JS side of my project without updating any packages or something but now I get these errors..

Task :app:checkReleaseDuplicateClasses FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkReleaseDuplicateClasses'.
> 1 exception was raised by workers:
  java.lang.RuntimeException: java.lang.RuntimeException: Duplicate class com.google.android.gms.internal.measurement.zzbv found in modules classes.jar (com.google.android.gms:play-services-measurement-base:17.1.0) and classes.jar (com.google.android.gms:play-services-measurement-impl:17.0.1)
  Duplicate class com.google.android.gms.internal.measurement.zzbw found in modules classes.jar (com.google.android.gms:play-services-measurement-base:17.1.0) and classes.jar (com.google.android.gms:play-services-measurement-impl:17.0.1)

..... continues

So probably some packages are making this conflict which use google play services, so here is my package.json.

{
  "name": "xx",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.6.1",
    "@react-native-firebase/app": "^0.2.3",
    "@react-native-firebase/database": "^0.2.3",
    "axios": "^0.19.0",
    "immutable": "^4.0.0-rc.12",
    "react": "16.8.6",
    "react-native": "0.60.4",
    "react-native-admob": "^2.0.0-beta.6",
    "react-native-device-info": "^2.3.2",
    "react-native-gesture-handler": "^1.3.0",
    "react-native-iap": "^3.3.7",
    "react-native-image-picker": "^1.0.2",
    "react-native-indicators": "^0.13.0",
    "react-native-onesignal": "^3.5.0",
    "react-native-progress": "^3.6.0",
    "react-native-sound": "^0.11.0",
    "react-native-swiper": "^1.5.14",
    "react-navigation": "^3.11.1",
    "react-redux": "^7.1.0",
    "redux": "^4.0.4",
    "redux-logger": "^3.0.6"
  },
  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/runtime": "^7.5.5",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.8.0",
    "eslint": "^6.1.0",
    "jest": "^24.8.0",
    "metro-react-native-babel-preset": "^0.55.0",
    "react-test-renderer": "16.8.6"
  },
  "jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|react-navigation)/"
    ],
    "preset": "react-native"
  }
}

android/build.gradle

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

        // 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()
    }
}

android/app/build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile

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

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

    /**
     * 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 "xx"
            minSdkVersion rootProject.ext.minSdkVersion
            targetSdkVersion rootProject.ext.targetSdkVersion
            versionCode 50
            versionName "1.0"
            multiDexEnabled true
        }
        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'
            }
            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
                 }
             }
        }
        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.
                minifyEnabled enableProguardInReleaseBuilds
                proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
                signingConfig signingConfigs.release
            }
        }
        // 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
                }

            }
        }

        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 fileTree(dir: "libs", include: ["*.jar"])
        implementation "com.facebook.react:react-native:+"  // From node_modules
        implementation 'com.android.support:multidex:1.0.3'

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

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

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

i get 'com.facebook.jni.CppException: Could not get BatchedBridge, make sure your bundle is packaged correctly...' error from react native signed apk

$
0
0
com.facebook.jni.CppException: Could not get BatchedBridge, make sure your bundle is packaged correctly
        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
        at android.os.Looper.loop(Looper.java:201)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:232)
        at java.lang.Thread.run(Thread.java:764)

this the error that i get from android studio logcat also from my phone bug report screen. this error happened when i published app in play store and its ok when i install it directly from terminal with react-native run-android --variant=release

react-native version: 0.60.4 enableHermes: true

React Native - Keep React Navigation Stack Header from moving with KeyboardAvoidingView (Android)

$
0
0

I have a messaging page in my application that is part of a React-Navigation-Stack and has a header with a back button. The messages are contained within KeyboardAvodingView and ScrollView, but when I open the keyboard on android I lose the header. I've played with settings in the AndroidManifest file, currently using android:windowSoftInputMode="adjustPan" but have not been able to fix the issue. I've also seen other people have this issue due to but none of the their solutions solved the issue.

enter image description here

import React, { useState, useEffect, useRef } from 'react'
import { StyleSheet, View, Text, TextInput, ScrollView, KeyboardAvoidingView, Platform, NativeModules, SafeAreaView, Keyboard } from 'react-native'
import Message from './message'


let Messages = props => {
  let { StatusBarManager } = NativeModules
  let scrollViewRef = useRef()

  let [messages, setMessages] = useState([])
  let [keyboardPadding, setKeyboardPadding] = useState(0)
  let [statusBarHeight, setStatusBarHeight] = useState(0)

  useEffect(() => {
    Platform.OS == 'ios' ? StatusBarManager.getHeight((statusBarFrameData) => {
      setStatusBarHeight(statusBarFrameData.height)
    }) : null 
    let keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', keyboardWillShow)
    let keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', keyboardWillHide)

    return () => {
      keyboardWillShowListener.remove()
      keyboardWillHideListener.remove()
    }
  }, [messages, keyboardPadding])


  let keyboardWillShow = (e) => {
    setKeyboardPadding(1)
  }

  let keyboardWillHide = () => {
    setKeyboardPadding(0)
  }

  let scrollStyles = (keyboardPadding) => {
    return { paddingBottom: keyboardPadding }
  }

  let renderMessages = (messages) => {
    return messages.map((data, i) => <Message data={data} key={i}/>)
  } 

  let addMessage = (message) => {
    let messageObj = {
      message: message,
      userId: 2,
      userName: 'Sean'
    }
    setMessages([...messages, messageObj])
  }

  return (
    <SafeAreaView style={styles.container}>
        <KeyboardAvoidingView 
          style={styles.keyboardContainer}
          behavior={Platform.OS == 'ios' ? 'padding' : null}
          keyboardVerticalOffset={statusBarHeight + 44}
        >
          <ScrollView 
            ref={scrollViewRef}
            onContentSizeChange={(contentWidth, contentHeight)=> {scrollViewRef.current.scrollToEnd({animated: true})}}
          >
            <View style={scrollStyles(keyboardPadding)}>
              {renderMessages(messages)}
            </View>
          </ScrollView>
          <View style={styles.textBox}>
            <TextInput 
              style={styles.textInput}
              placeholder='Reply...'
              placeholderTextColor={'rgb(216,216,216)'}
              returnKeyType='done'
              autoCapitalize='none'
              selectionColor='#3490dc'
              multiline={true}
              blurOnSubmit={true}
              onSubmitEditing={(e)=> addMessage(e.nativeEvent.text)}
            />
          </View>  
        </KeyboardAvoidingView>  
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: 'rgb(0,0,0)'
    },
    keyboardContainer: {
      flex: 1,
      backgroundColor: 'rgb(0,0,0)'
    },
    textInput: {
      color: 'rgb(255,255,255)',
      fontSize: 18,
    },
    textBox: {
      borderColor: '#242F39',
      borderWidth: 1,
      borderRadius: 2, 
      padding: 10,
      paddingLeft: 16,
      backgroundColor: '#0A151F',
    },
})

export default Messages

React native fetch api does not work with localhost, IP, or even 10.0.2.2

$
0
0

I am using expo client on my android device and have setup up a django server at localhost:8000 and i'm trying to access and endpoint using fetch in react native. I have looked at How can I access my localhost from my Android device?How do you connect localhost in the Android emulator? and How to connect to my http://localhost web server from Android Emulator in Eclipse but that did not work.

I also tried using my machine's ip address instead of localhost, but no results. Here is a sample code

componentDidMount(){
    return fetch('http://my-ip-address:8000/restapi/')
      .then((response) => {
        console.log("success")
        response = response.json()
      }).catch(error => {
        console.error(error)
      })
  }

What am I doing wrong here?

"Getting Started" Guide for React Native Not Working with Android Device

$
0
0

I've been trying to get the basic React Native program up and running on my Windows PC, and cannot get it to load on my Pixel 3 which is connected through USB. I've done a fresh install of Node.js to 12.13.1. Here's what I get when I do npx react-native run-android

PS C:\Users\davidc\Working\AwesomeProject> npx react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 864 file(s) to forward-jetify. Using 8 workers...
info Starting JS server...
* daemon not running; starting now at tcp:5037
* daemon started successfully
info Installing the app...
Starting a Gradle Daemon, 2 incompatible and 1 stopped Daemons could not be reused, use --status for details

> Task :app:installDebug
03:53:33 V/ddms: execute: running am get-config
03:53:33 V/ddms: execute 'am get-config' on '891X0457A' : EOF hit. Read: -1
03:53:33 V/ddms: execute: returning
Installing APK 'app-debug.apk' on 'Pixel 3 - 10' for app:debug
03:53:33 D/app-debug.apk: Uploading app-debug.apk onto device '891X0457A'
03:53:33 D/Device: Uploading file onto device '891X0457A'
03:53:33 D/ddms: Reading file permision of C:\Users\davidc\Working\AwesomeProject\android\app\build\outputs\apk\debug\app-debug.apk as: rwx------
03:53:34 V/ddms: execute: running pm install -r -t "/data/local/tmp/app-debug.apk"
03:53:37 V/ddms: execute 'pm install -r -t "/data/local/tmp/app-debug.apk"' on '891X0457A' : EOF hit. Read: -1
03:53:37 V/ddms: execute: returning
03:53:37 V/ddms: execute: running rm "/data/local/tmp/app-debug.apk"
03:53:37 V/ddms: execute 'rm "/data/local/tmp/app-debug.apk"' on '891X0457A' : EOF hit. Read: -1
03:53:37 V/ddms: execute: returning
Installed on 1 device.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 32s
27 actionable tasks: 27 executed
info Connecting to the development server...
8081
info Starting the app on "891X0457A"...
Starting: Intent { cmp=com.awesomeproject/.MainActivity }
PS C:\Users\davidc\Working\AwesomeProject>

That's all I can get it to do. My phone says it's unable to load script, and to make sure metro server is running or index.android.bundle has been packaged correctly. Any suggestions?


How to create android widget using react native?

$
0
0

Is it possible to make android widget using react-native? I have done some search to find an approach but only find this repo

Is it any other approach to make android widget using react-native?

How to reduce Reactive Native app memory usage in Android

$
0
0

As soon as I run my app, it takes up about 250MB of memory. I checked the heap of android studio byte [], char [], long [] occupy a huge amount of memory. What can I do to my reactive code to reduce the memory equivalent of byte []?

I don't know anything because it is only represented as byte [].enter image description here

ReactNative Metro Bundler not starting automatically

$
0
0

react-native run-android not starting bundler so i tried react-native start it showing below error.

┌──────────────────────────────────────────────────────────────────────────────┐
│                                                                              │
│  Running Metro Bundler on port 8081.                                         │
│                                                                              │
│  Keep Metro running while developing on any JS projects. Feel free to        │
│  close this tab and run your own Metro instance if you prefer.               │
│                                                                              │
│  https://github.com/facebook/react-native                                    │
│                                                                              │
└──────────────────────────────────────────────────────────────────────────────┘

events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::8081
    at Server.setupListenHandle [as _listen2] (net.js:1286:14)
    at listenInCluster (net.js:1334:12)
    at Server.listen (net.js:1421:7)
    at /Users/user/Documents/Prasanth/AwesomeProject/node_modules/metro/src/index.js:157:18
    at new Promise (<anonymous>)
    at Object.<anonymous> (/Users/user/Documents/Prasanth/AwesomeProject/node_modules/metro/src/index.js:156:12)
    at Generator.next (<anonymous>)
    at step (/Users/user/Documents/Prasanth/AwesomeProject/node_modules/metro/src/index.js:47:262)
    at /Users/user/Documents/Prasanth/AwesomeProject/node_modules/metro/src/index.js:47:422
Emitted 'error' event at:
    at Server.WebSocketServer._onServerError (/Users/user/Documents/Prasanth/AwesomeProject/node_modules/ws/lib/WebSocketServer.js:82:50)
    at Server.emit (events.js:187:15)
    at emitErrorNT (net.js:1313:8)
    at process._tickCallback (internal/process/next_tick.js:63:19)

react-native info

  React Native Environment Info:
    System:
      OS: macOS High Sierra 10.13.6
      CPU: x64 Intel(R) Core(TM)2 Duo CPU     E7600  @ 3.06GHz
      Memory: 3.36 GB / 12.00 GB
      Shell: 3.2.57 - /bin/bash
    Binaries:
      Node: 10.12.0 - /usr/local/bin/node
      Yarn: 1.10.1 - /usr/local/bin/yarn
      npm: 6.4.1 - /usr/local/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
      Android SDK:
        Build Tools: 21.1.2, 23.0.1, 25.0.0, 26.0.0, 26.0.1, 26.0.2, 26.0.3, 27.0.3, 28.0.2, 28.0.3
        API Levels: 21, 22, 23, 24, 25, 26, 27
    IDEs:
      Android Studio: 3.2 AI-181.5540.7.32.5056338
      Xcode: 10.0/10A255 - /usr/bin/xcodebuild
    npmPackages:
      react: 16.5.0 => 16.5.0 
      react-native: 0.57.2 => 0.57.2 
    npmGlobalPackages:
      react-native-cli: 2.0.1
      react-native-git-upgrade: 0.2.7

package.json

{
  "name": "AwesomeProject",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.5.0",
    "react-native": "0.57.2"
  },
  "devDependencies": {
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "react-test-renderer": "16.5.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

I tried cleaning cache and reverse adb still am getting that issue

react-native run-android showing below error.

enter image description here

Android Home configuration

export ANDROID_HOME=/<Path>/android-sdk-macosx
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
export PATH=$PATH:$ANDROID_HOME/emulator

How to resolve this issue.

react-native push notification onNotification doesn't trigger

$
0
0

I am using zo0r react-native-push-notification library.

"react": "16.0.0-alpha.12",
"react-native": "^0.45.1",
"react-native-push-notification": "^3.0.0"

This code runs every time I open an app:

PushNotification.configure({
    onNotification: function(notification) {
        console.log('onNotification');
        ToastAndroid.show('onNotification', 3000);
    }
});

I send local push notification from background service:

PushNotification.localNotification({
    message: 'Hello World',
    smallIcon: 'ic_launcher'
});

The notification gets delivered. When I click it, onNotification method doesn't get called, then when I receive another notification, it actually gets called. It seems like it works only if app is in memory atm.

Am I doing something wrong?

I have opened a GitHub issue as well.

Could not find com.google.firebase:firebase-bom:12.0.1

$
0
0

I am migrating from react-native-google-analytics-bridge to react-native-firebase. I followed the steps to add the package to my android project. At first I got an error saying method platform is not available. Most of the stackoverflow posts said to upgrade the gradle from 3.1.3 to a higher version. So, I updated it to 3.5.0 plugin and 5.6.4 gradle version.

Now, On running the command 'react-native run-android', I am getting the below error:

Could not determine the dependencies of task ':@react-native-firebase_app:compileDebugAidl'.
> Could not resolve all task dependencies for configuration ':@react-native-firebase_app:debugCompileClasspath'.
   > Could not find com.google.firebase:firebase-bom:12.0.1.
     Required by:
         project :@react-native-firebase_app

Can someone help with any possible solution to this.

More details: android/build.gradle file

dependencies {
   classpath 'com.android.tools.build:gradle:3.5.0'
   classpath 'com.google.gms:google-services:4.3.2'
}

android/app/build.gradle file:

dependencies {
    implementation project(path: ":@react-native-firebase_app")
}

apply plugin: 'com.google.gms.google-services'
Viewing all 28476 articles
Browse latest View live


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