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

Disable default focus behaviour on Android TV

$
0
0

we've built the custom focus manager on Android TV, unfortunately, we can not find the way how to disable default focus behaviour. The problem appears when we are putting our elements in the ScrollView. The View is being scrolled to follow the default focus pointer. The problem is that our focusManager works in a different way and it goes out of sync with the default one, resulting in view moving away from our focused item.

We tried the following:

  • Removing all Tocuahbles and replacing them with a custom class.
  • Replacing ScrollView with FlatList
  • Trying to set scrollEnabled={false}
  • Trying to call preventDefault onFocus/onScroll events.

Nothing seems to work.

We are using RN 0.59.10

enter image description here


invalid resource directory name, drawable-anydpi-v21

$
0
0

I would like to build my application and send it over to my samsung tablet using android 4.2.2. But I would like to have my application compatible with newer versions too (i.e. API 23)

I start the application using this command :

react-native run-android

When it's building I receive this error, I clean the project twice already with no success. I do not use eclipse or android studio.

:app:processDebugResourcesinvalid resource directory name: D:\Projects\react-native\project\android\app\build\intermediates\res\merged\debug/drawable-anydpi-v21

This is a part of the gradle file.

android {    compileSdkVersion 17    buildToolsVersion "19.1.0"    defaultConfig {        applicationId "com.project"        minSdkVersion 17        targetSdkVersion 23        ...    }    dependencies {        compile fileTree(dir: "libs", include: ["*.jar"])        compile "com.android.support:appcompat-v7:18.0.+"        compile "com.facebook.react:react-native:+"  // From node_modules    }

View moves out of the screen when Text Input is focused used on Bottom Sheet in React Native for Android

$
0
0

I'm using the library - https://github.com/osdnk/react-native-reanimated-bottom-sheet

I'm using a TextInput on this bottom sheet. And now when the Text Input is focused or typed in, the bottom sheet should remain at the same position. It works fine for iOS, shown in the below screenshot.

enter image description here

And when I focus the Text Input on Android, the bottom sheet moves up along with the keyboard, shown in below 2 screenshots.

(Bottom Sheet in Android not focused)

enter image description here

(Bottom Sheet in Android focused)

enter image description here

I've also tried wrapping my bottom sheet inside KeyboardAvoidingView and its props accordingly but it didn't work.

React Native Android Fetch failing on connection to local API

$
0
0

I'm using the fetch API in my react-native Android app to make requests to a local API. I usually query said API from react web apps at http://localhost:8163.

I'm testing my app on my physical device in debugger mode. I read somewhere that react-native can't query localhost the same way a web app can. Apparently you have to use http://10.0.2.2:[PORT_NUMBER_HERE]/ which is an alias for `http://127.0.0.1:[PORT_NUMBER_HERE] according to the the Android emulator docks. I'm not sure if this is what I'm supposed to be doing for testing on a physical device.

My fetch code looks like the following:

fetchToken() {    fetch('http://10.0.2.2:8163/extension/auth', {        method: 'GET',        headers: {'Accept': 'application/json','Content-type': 'application/json'        }    })    .then((response)) => console.log('successful fetchToken response: ', response.json()))    .catch((error) => console.log('fetchToken error: ', error))    .done();}

The request always hangs for a while and then reaches the catch block with the unhelpful error TypeError: Network request failed(...). Checking the logs for my local API, they don't register the request at all.

So I have no idea if I'm querying my local API correctly to get the resource that I want, and if I am, I don't know why the fetch is failing.

Undefined return value using useState and firebase for objects in React Native

$
0
0

I'm writing an app using React Native and I came across an issue when trying to update an Object with the useState method. Here's my code:

const Screen = ({route}) => {    var roomKey = route.params;    const [room, setRoom] = useState({});    db.ref('rooms').on('value', (data) => {        setRoom(() => (data.val())[roomKey]);    });    console.log(room);// rest of the code ...

My code works as follows: first it takes a key outputted by another screen with react navigation, and then calls the firebase database with the ref method (db is defined as Firebase.initializeApp(config).database(), where config is the object with all the firebase datas needed). If I log out the data.val())[roomKey] it correctly outputs the object I'm downloading from database, however the room object is not updated by the useState method (it outputs undefined, making the following part of the code crash). What am I doing wrong?

How to solve this Firebase auth/rejected-credential

$
0
0

This is my code that im doing auth. I've used @react-native-firebase/auth for this. I've downloaded google-services.json file and placed in the android folder.

Now if I run the code and after entering the Phone Number It is throwing error that:

[Error: [auth/rejected-credential] The request contains malformed or mismatching credentials [ App ID does not match requested project. ]]

How to solve this?

handleSendCode = () => {    // Request to send OTP    if (this.validatePhoneNumber()) {      auth()        .signInWithPhoneNumber(this.state.phone)        .then(confirmResult => {          this.setState({ confirmResult })        })        .catch(error => {          alert(error.message)          console.log(error)        })    } else {      alert('Invalid Phone Number')    }  }

React Native Firebase auth().signInWithPhoneNumber() return unexpected error in Release APK

$
0
0

I have been working on react native app development which I've already built a released version. unfortunately, released version has caused me an unexpected error when the app is calling auth().signInWithPhoneNumber() function. In contrary, the debug version does not cause any problem.

As I couldn't get any logs in released app, I've taken a step further to logged down the error message. It turned out that, the return error message from firebase was

{{'line': 101, 'column': 244, 'sourceURL': 'index.android.bundle'}}

Therefore, I have put some researched on index.android.bundle, it seem that the resources in google were all about JS did not bundle it correctly. In such case, without hesitation I would try any solutions that I could search online.

One of the solution I've followed washttps://medium.com/@shreyasnisal/solved-packing-error-in-react-native-release-apk-f887687edc4f

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

There is no luck on solving this issue as well.

The codes following where the error returns

async function signInWithPhoneNumber(phoneNumber: string, event: any) {    event.preventDefault();    try {      const confirmation = await auth().signInWithPhoneNumber(phoneNumber);      if (confirmation) {        setConfirm(confirmation);      }    } catch (err) {      console.log('Check Exist Error2 - '+ err.message);      console.log('error Code - '+ err.code);      setErrorOccured(true);      if (err.code === 'missing-phone-number') {        console.log('Missing Phone Number.');        setErrorMsg('Missing Phone Number.');      } else if (err.code === 'auth/invalid-phone-number') {        console.log('Invalid Phone Number.');        setErrorMsg('Invalid Phone Number.');      } else if (err.code === 'auth/quota-exceeded') {        console.log('SMS quota exceeded.');        setErrorMsg('SMS quota exceeded.Please try again later.');      } else if (err.code === 'auth/user-disabled') {        console.log('User disabled.');        setErrorMsg('Phone Number disabled. Please contact support.');      } else {        console.log('Unexpected Error.'+ err.code);        axios.post(`https://myapi/error`, err);        setErrorMsg('Unexpected Error Occured. Please contact support.');      }    }  }

Here's my build.gradle

apply plugin: "com.android.application"apply plugin: 'io.fabric'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. If none specified and    // "index.android.js" exists, it will be used. Otherwise "index.js" is    // default. Can be overridden with ENTRY_FILE environment variable.    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 = [    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 {    dexOptions {       javaMaxHeapSize "3g"    }    compileSdkVersion rootProject.ext.compileSdkVersion    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    defaultConfig {        applicationId "com.test.testtrace"        minSdkVersion rootProject.ext.minSdkVersion        targetSdkVersion rootProject.ext.targetSdkVersion        versionCode 1        versionName "1.0"        multiDexEnabled true        missingDimensionStrategy 'react-native-camera', 'general'    }    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 {            storeFile file('.keystore')            storePassword '-'            keyAlias '.keystore'            keyPassword '-'        }    }    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.release            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"        }    }    packagingOptions {        pickFirst "lib/armeabi-v7a/libc++_shared.so"        pickFirst "lib/arm64-v8a/libc++_shared.so"        pickFirst "lib/x86/libc++_shared.so"        pickFirst "lib/x86_64/libc++_shared.so"    }    // 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            }        }    }}crashlytics {  enableNdk true}dependencies {    implementation fileTree(dir: "libs", include: ["*.jar"])    //noinspection GradleDynamicVersion    implementation "com.facebook.react:react-native:+"  // From node_modules    implementation project(path: ":@react-native-firebase_crashlytics")    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"    implementation project(':lottie-react-native')    implementation project(':react-native-splash-screen')    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {      exclude group:'com.facebook.fbjni'    }    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {        exclude group:'com.facebook.flipper'    }    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {        exclude group:'com.facebook.flipper'    }    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 usetask 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'

Please help me to look at this issue as I wished to launch my app as soon as possible.

Thank you

Managing app version when publish to google play

$
0
0

I'm about to publish my first app on google play and I'm a little bit lost on how to manage my app version. I have my frontend app written with react native and I have a backend server built with spring boot.

In my backend I have my version number which is incremented on each build release.

My problem is that I don't know how to manage versioning in the react-native part: there's a version tag in package.json and I read here that I should increment versionCode in AndroidManifest file.

To summarize here are my questions:

1/ Should version in my backend, in package.json and in manifest file be always the same ?

2/ Is there a way to force user to update the app when I publish a new update on google play?

3/ When I publish a new version of the app, does users need to download full app size or there's a way to allow them to just download a partial size?

4/ If there's a mismatch between frontend and backend versions, users can perform actions or call some apis that aren't available anymore in my server, how can I prevent this to happen?

I know I asked many questions in one but as I said that's the first time I publish to google play and I wanted to separate my question on 4 parts to be more clear.


React-Native: Hermes is not enabled

$
0
0

I am trying to enable Hermes in a new project but despite I have enabled it in android/app/build.gradle it is not enabled. I am not able to see Engine: Hermes text in app as described in documentation. I am using WebStorm 2019.2 project template.

App.js:

// importsconst App = () => {  return (<Fragment><StatusBar barStyle="dark-content"/><SafeAreaView><ScrollView          contentInsetAdjustmentBehavior="automatic"          style={styles.scrollView}><Header/>          {global.HermesInternal == null ? null : (<View style={styles.engine}><Text style={styles.footer}>Engine: Hermes</Text></View>          )}          // rest of the default ui omitted</ScrollView></SafeAreaView></Fragment>  );};export default App;

babel.cofig.js:

module.exports = {  presets: ['module:metro-react-native-babel-preset'],};

metro.config.js:

module.exports = {  transformer: {    getTransformOptions: async () => ({      transform: {        experimentalImportSupport: false,        inlineRequires: false      }    })  }};

package.js:

{"name": "hermes","version": "0.0.1","private": true,"scripts": {"start": "react-native start","test": "jest","lint": "eslint ."  },"dependencies": {"react": "16.8.6","react-native": "0.60.4"  },"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": {"preset": "react-native"  }}

You can checkout and test the project from here.

UPDATE:

I have manged to enable both Hermes and auto linking after upgrading to RN v0.62.2. Here is my current settings and dependencies:

Android app built with React Native and Expo still asking for app permissions

$
0
0

I built an Android app using React Native and building the apk file using expo expo build:android. However, when I run the app on an emulator, even after removing all permissions form AndroidManifest.xml, the app still asks for Physical Activity permissions:

android/app/src/main/AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="<package.name>"><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/><!-- OPTIONAL PERMISSIONS, REMOVE WHATEVER YOU DO NOT NEED --><!-- These require runtime permissions on M --><!-- END OPTIONAL PERMISSIONS --><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"><meta-data android:name="expo.modules.updates.EXPO_UPDATE_URL" android:value="YOUR-APP-URL-HERE" /><meta-data android:name="expo.modules.updates.EXPO_SDK_VERSION" android:value="YOUR-APP-SDK-VERSION-HERE" /><activity    android:name=".MainActivity"    android:label="@string/app_name"    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"    android:launchMode="singleTask"    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" /></application>

Permissions Screenshot

I have tried adding the tools:node="remove" tag rather than removing the uses-permissions lines but this had no effect.

My app requires no permissions and this issue is preventing me from uploading to the Play Store. I read in other posts that a library I am using might be requesting permissions but I do not believe any of the npm libraries I am using would require any such permissions:

package.json

{"main": "index.js","scripts": {"android": "react-native run-android","ios": "react-native run-ios","web": "expo start --web","start": "react-native start","test": "jest" },"dependencies": {"av": "^0.4.9","expo": "~37.0.3","expo-av": "^8.1.0","expo-updates": "~0.1.0","react": "~16.9.0","react-dom": "~16.9.0","react-native": "~0.61.5","react-native-elements": "^2.0.0","react-native-gesture-handler": "~1.6.0","react-native-modal": "^11.5.6","react-native-popup-dialog": "^0.18.3","react-native-reanimated": "~1.7.0","react-native-responsive-fontsize": "^0.4.3","react-native-responsive-screen": "^1.4.1","react-native-screens": "~2.2.0","react-native-unimodules": "~0.9.0","react-native-web": "~0.11.7" },"devDependencies": {"@babel/core": "~7.9.0","babel-jest": "~25.2.6","jest": "~25.2.6","react-test-renderer": "~16.9.0" },"jest": {"preset": "react-native" },"private": true}

Any help would be appreciated.

Deeplinked screen automatically returning to previous screen - ReactNative Android

$
0
0

I'm creating a notification reminder application in react native, I tried opening a specific screen in the application when user taps on the notification, I'm using react-navigation and tried deep linking with the screen paths. so my problem is, the deep-linked screen is opening fine when the app is foreground already, but if I open the notification when the app is closed(even not in recent), it goes to the deep-linked screen and immediately going back to the previous screen.

I'm doing some async operations in the useEffect. not sure if this is the issue, help can be greatly appreciated.

useEffect(() => {   const paramObject = navigation.getParam('someObject', {});   if (Object.keys(paramObject).length === 0) {      const resourceID = navigation.getParam('resource_id', '');      const target = navigation.getParam('target', '');      axios.get().then(() => {       // some state setting       }).catch(); #Some api call   }}, []);

Note: Problem occurs when the deeplink page opens when the app is closed, I'm also getting some warnings with the problem like Can't Perform react state update on a unmounted component ...

How to get status of playback (media player) on device and listen for changes using expo react-native app?

$
0
0

I'm trying to get information from the now playing playback of an ios and android device for my expo react-native app and listen for changes. I'm trying to use expo-av but can't seem to accomplish this. Any help is greatly appreciated. I would like to stick with expo if possible.

Expo Speech resume and pause methods not working on Android - React Native

$
0
0

Expo Speech’s resume and pause methods are not working on the Android Platform. However they work just fine on the iOS Platform. I can’t move away from Expo. So is there a way I can use expo and still achieve the functionality, Kindly help.

Expo SDK Version: 37Platforms(Android/iOS/web/all): Android

How to securely store 3rd Party API keys when back end is provided entirely by 'Back End As A Service'?

$
0
0

I am trying to develop a strategy for securing third party API keys for a React Native app. When building a web application, API keys can be stored in environment variables and then secured when deploying the application server.

However with a mobile app that only uses 'back end as a service' back end services, like Firebase, the app is not deployed, it is distributed and services are accessed.

After doing some research, it seems there is no standard / straight forward approach to solving this problem although it must be a situation that thousands of app developers find themselves in.

I am using Firebase, but also two other services that require API keys. My initial solution was to add these API keys (not Firebase keys) to Firebase environment variables as described here and then make a call in the app to a Firebase Cloud Function and to retrieve them. But I think the problem might be here that the keys can still be intercepted as they will be retrieved in plain text.

Is this a good approach to storing the third party keys, and if not, what other approaches could be taken?

Thanks in advance.

Unhandled promise rejection: TypeError: Network request failed expo node backend

$
0
0

I have a node backend that my expo app is querying. The node-express-mongo backend works just perfect which I can verify using GET Request from Postman but I get unhandled promise rejection Network Failed error in my app

Complete error:

[Unhandled promise rejection: TypeError: Network request failed]- node_modules/whatwg-fetch/dist/fetch.umd.js:473:29 in xhr.onerror- node_modules/event-target-shim/dist/event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:574:29 in setReadyState- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:388:25 in __didCompleteResponse- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:190:12 in emit- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0* [native code]:null in callFunctionReturnFlushedQueue

here's my code:

api.js

export const fetchMeetups = () =>    fetch('http://localhost:3000/api/meetups')        .then(res => res.json());

App.js

import * as React from 'react';import { Platform, StyleSheet, Text, View, ActivityIndicator } from 'react-native';import { fetchMeetups } from './constants/api'; const instructions = Platform.select({  ios: `Press Cmd+R to reload,\nCmd+D or shake for dev menu`,  android: `Double tap R on your keyboard to reload,\nShake or press menu button for dev menu`,});class App extends React.Component{  static defaultProps = {    fetchMeetups  }  state = {    loading: false,    meetups: []  }  async componentDidMount(){    this.setState({loading: true});    const data = await this.props.fetchMeetups();    setTimeout(() => this.setState({loading: false, meetups: data.meetups}),2000)  }  render(){    if(this.state.loading){      return(<ActivityIndicator size="large"/>      )    }    return (<View style={styles.container}><Text>MeetupME</Text></View>    );  }}const styles = StyleSheet.create({  container: {    flex: 1,    justifyContent: 'center',    alignItems: 'center',    backgroundColor: '#F5FCFF',  },  welcome: {    fontSize: 20,    textAlign: 'center',    margin: 10,  },  instructions: {    textAlign: 'center',    color: '#333333',    marginBottom: 5,  },});

index.js

import { registerRootComponent } from 'expo';import App from './App';// registerRootComponent calls AppRegistry.registerComponent('main', () => App);// It also ensures that whether you load the app in the Expo client or in a native build,// the environment is set up appropriatelyregisterRootComponent(App);

--------------UPDATE------------------added a catch block to fetch & getting this new error

Network request failed- node_modules/whatwg-fetch/dist/fetch.umd.js:473:29 in xhr.onerror- node_modules/event-target-shim/dist/event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:574:29 in setReadyState- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:388:25 in __didCompleteResponse- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:190:12 in emit- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0* [native code]:null in callFunctionReturnFlushedQueue

emulator

postman


Persistent React Native problem: JAVA_HOME is not set

$
0
0

I'm trying to create a React Native app for Android on Windows 10, but every time I use react-native run-android I get the same Error: ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

I've already set up this variable via the Control Panel

And I've set up the Path variable to both the JDK and JRE

I've uninstalled and reinstalled the JDK and Android Studio, I have tried removing and adding "\bin" to both the Path and JAVA_HOME variables, and I've been browsing similar questions (including this one and this one) to no avail.

What can I do?

How to take a picture and get the data in React Native with the mobile camera

$
0
0

Before you say this is a duplicate let me explain.I know how to use Camera in React Native, but in Android(Java) last month I managed the device camera in a simple way, I not even had to make a new View to use it. I just did something like this:

Uri mOutputFileUri;Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutputFileUri); // URI of the file where pic will be storedstartActivityForResult(intent, TAKE_PICTURE_FROM_CAMERA);

Basically this automatically open the camera and when press "to take photo button" the method onActivityForResult() is called, getting image data to manage.

So, my doubt is, there is a way to do this in React Native? I mean, calling a method that automatically open the camera and return the data?

Thanks a lot.

how to Build For TV Devices in react native using functional components?

$
0
0

this is the example Given on react native website about Building For TV Devices:URL

var TVEventHandler = require('TVEventHandler');class Game2048 extends React.Component {  _tvEventHandler: any;  _enableTVEventHandler() {    this._tvEventHandler = new TVEventHandler();    this._tvEventHandler.enable(this, function(cmp, evt) {      if (evt && evt.eventType === 'right') {        cmp.setState({board: cmp.state.board.move(2)});      } else if(evt && evt.eventType === 'up') {        cmp.setState({board: cmp.state.board.move(1)});      } else if(evt && evt.eventType === 'left') {        cmp.setState({board: cmp.state.board.move(0)});      } else if(evt && evt.eventType === 'down') {        cmp.setState({board: cmp.state.board.move(3)});      } else if(evt && evt.eventType === 'playPause') {        cmp.restartGame();      }    });  }  _disableTVEventHandler() {    if (this._tvEventHandler) {      this._tvEventHandler.disable();      delete this._tvEventHandler;    }  }  componentDidMount() {    this._enableTVEventHandler();  }  componentWillUnmount() {    this._disableTVEventHandler();  }

but I am using functional components and I don't know how to convertcan someone show me How?

How to upload Image on server using ReactNative

$
0
0

I am setting headers and body , Using fetch with Post to upload image on server.I am getting the response code 200 but it is not uploading image but rest of the Data is getting uploaded.

Here is the code of body:

export default function setRequestBody(imagePath){    let boundry = "----WebKitFormBoundaryIOASRrUAgzuadr8l";    let body = new FormData();    body.append("--"+boundry+"\r\n");    body.append("Content-Disposition: form-data; name=imageCaption\r\n\r\n");    body.append("Caption"+"\r\n");    body.append("--"+boundry+"\r\n");    body.append("Content-Disposition: form-data; name=imageFormKey; filename =iimageName.pngg \r\n");    body.append("Content-Type: image/png \r\n\r\n");    body.append({uri : imagePath});    // appened image Data Here    body.append("\r\n");    body.append("--"+boundry+"--\r\n");    return body}

Please help.What mistake I am making. :(

React Native Navigation React Native CLI Autolinking error

$
0
0

Issue Description

I installed the library via npx react-native link react-native-navigation (and modifying the minSdkVersion in andoid/build.gradle).

When I run npx react-native run-android, the app is built and works fine, though I get the following error in the terminal:

error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:   - react-native-navigation (to unlink run: "react-native unlink react-native-navigation")

Since the lib has been linked manually, I add an entry in the react-native.config.js file to prevent react native to try to autolink the lib, as in:

module.exports = {    dependencies: {'react-native-navigation': {            platforms: {                android: null, // disable Android platform, other platforms will still autolink if provided            },        }    }  };

Now, the CLI error is not longer shown and the app is successfully built, but I get an error in the emulator:

TypeError: null is not an object (evaluating "this.nativeCommandsModule.setRoot()").

Which comes about at my first Navigation.setRoot(...); call:

[index.js]const start = () => {    Navigation.events().registerAppLaunchedListener(() => {        registerScreens();        gotoInitialising();        // gotoLogin();    });};start();

My question is, what extra step should I take to get the lib to work and to not have a React Native CLI error, at the same time.

Environment

React Native Navigation version: 6.0.1React Native version: 0.61.5Platform(s) (iOS, Android, or both?): AndroidDevice info (Simulator/Device? OS version? Debug/Release?): Android emulator API 28 - (emulator version 29.2.1-5889189) - Debug build

Viewing all 28460 articles
Browse latest View live


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