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

How to recover user account if user has deleted the app or changed phone?

$
0
0

I am working with Cloud Firestore and I came to the question on the top. I will set you an example

  1. The user installs the app and log's in with Google. I save the log-in information in the device storage so the user does not have to log in every time. It is also stored in Firestore with a generated ID.
  2. The user plays with the app and one day uninstalls it. This erases the log-in information in the async storage, losing the generated ID that granted him access to the app.
  3. One day he decides to install it again, let's say in another device to make it harder. He had various information in his profile or maybe an active payment plan he forgot to delete and he wants to do it now. He clicks on google log in since it was how he did it, but now the profile information is gone because another account was created with another generated ID.

How to avoid this? I want the app to remember the user account in some way. The user account would be stored in my Firestore.


Error: Network Error Axios - Image React Native

$
0
0

Im trying to post an Image to server but axios throw an error saying

[Error: Network Error]

I created a bodyFormData and appended the following

bodyFormData.append('image', {          name: imgName,          type: 'image/jpeg',          uri: this.state.image,        });

where my imageName is just a string and the this.state.image is the file path file:///storage/emulated/0/Pictures/0cccb0f1-375b-44b8-b15b-4625536a8d63.jpg

Axios Call

const addProduct = async product => {  try {    var prod = await axios({      method: 'post',      url: baseURL +'addProduct',      data: product,      headers: {'content-type': `multipart/form-data; boundary=${product._boundary}`,    Accept: 'application/json',  },      },    });    return prod;  } catch (err) {    throw err;  }};

after alot of trials i understand that in bodyFormData even i write any kind of json object

const oj = {          name: 'a',          c: 8,        }bodyFormData.append('image', obj  );

it throws me the same error

[Error: Network Error]

Kindly please drop the best possible solution for the problem

Thank you for your precious time.

React native geolocation getCurrentPosition no reponse (android)

$
0
0

I have read and tested a lot of issues but I still can not get geolocation on Android.

I use navigator.geolocation.getCurrentPosition, on iOS everything works fine, but on Android I have no answer to this function, either success or error.

I have installed react-native-permissions to make sure that the user has activated the permissions but it does not change anything because it says that everything is "authorized".

I noticed that it came from GPS of the device. If I activate it manually, everyting works fine. However, I can not find a way to activate it for the user. On iOS, if GPS is not activated, I fall in the error callback and tell user to activate it, but on android, nothing is happennig.

I don't understand why I can't get geolocation only with getCurrentPosition (I have ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION in manifest).

Here a part of my code:

componentDidMount() {navigator.geolocation.getCurrentPosition(  (position) => {    //do my stuff with position value  },  (error) => {    Permissions.getPermissionStatus('location')    .then((response) => {      if (response !== "authorized") {        Alert.alert("Error","We need to access to your location",          [            {              text: "Cancel",              onPress: () => {                // do my stuff              }, style: 'cancel'            },            {              text: "Open Settings",              onPress: () => Permissions.openSettings()            }          ]        );      } else {        // do my stuff      }    });  },  { enableHighAccuracy: true, timeout: 2000, maximumAge: 1000 });}

Does anyone have any idea ?

Thank you

How to set zoom level in google map according to miles in react native?

$
0
0

I have react native application using react-native-maps,in which there is a feature to display near by users based on radius chosen by user that works fine using geocode. but I am facing problem to set zoom level of Map based on user radius? if user selects maximum meter of radius then map should display whole world? How can I achieve this? to set zoom level dynamically based on radius chosen by user?

to set radius used react-native-slider, How can set zoom level on slide of slider?

Native modules for sensors not available. Did react-native link run successfully?

$
0
0

I followed the first steps of the React Native tutorial here:

https://facebook.github.io/react-native/docs/getting-started.html

Then I want to read information from the device sensors.

For that I also followed this tutorial:

https://medium.com/react-native-training/using-sensors-in-react-native-b194d0ad9167

and ended up with this code (just copy/pasted from there):

// Reference:// https://medium.com/react-native-training/using-sensors-in-react-native-b194d0ad9167// https://react-native-sensors.github.ioimport React, { Component } from 'react';import {  StyleSheet,  Text,  View} from 'react-native';import { Accelerometer } from "react-native-sensors";const Value = ({name, value}) => (<View style={styles.valueContainer}><Text style={styles.valueName}>{name}:</Text><Text style={styles.valueValue}>{new String(value).substr(0, 8)}</Text></View>)export default class App extends Component {  constructor(props) {    super(props);    new Accelerometer({      updateInterval: 400 // defaults to 100ms    })      .then(observable => {        observable.subscribe(({x,y,z}) => this.setState({x,y,z}));      })      .catch(error => {        console.log("The sensor is not available");      });    this.state = {x: 0, y: 0, z: 0};  }  render() {    return (<View style={styles.container}><Text style={styles.headline}>          Accelerometer values</Text><Value name="x" value={this.state.x} /><Value name="y" value={this.state.y} /><Value name="z" value={this.state.z} /></View>    );  }}const styles = StyleSheet.create({  container: {    flex: 1,    justifyContent: 'center',    alignItems: 'center',    backgroundColor: '#F5FCFF',  },  headline: {    fontSize: 30,    textAlign: 'center',    margin: 10,  },  valueContainer: {    flexDirection: 'row',    flexWrap: 'wrap',  },  valueValue: {    width: 200,    fontSize: 20  },  valueName: {    width: 50,    fontSize: 20,    fontWeight: 'bold'  },  instructions: {    textAlign: 'center',    color: '#333333',    marginBottom: 5,  },});

Here is the full repository you can download and try right away:

$ git clone https://github.com/napolev/react-native-app$ cd react-native-app$ npm i$ expo start

My problem is that after I do: $ expo start I get the following error:

Native modules for sensors not available. Did react-native link run successfully?

as you can see on the following image:

enter image description here

Any idea about how can I make this work?

Thanks!

How do I resolve 'You need to have MainApplication in your project' in React native run-android

$
0
0

I ejected from expo, and trying react-native run-android, I'm getting this error;

FAILURE: Build failed with an exception.* Where:Script 'C:\Users\simil\OneDrive\Documents\Codes\react-native\expo\doc\node_modules\react-native-unimodules\gradle.groovy' line: 81* What went wrong:A problem occurred evaluating project ':app'.> You need to have MainApplication in your project* 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.orgBUILD FAILED in 14s

This is my MainActivity path

MyApp\android\app\src\main\java\com\com.example.eg\MainActivity.java

Building React Native app fails: Task :app:generateDebugBuildConfig FAILED

$
0
0

I am trying to run an app on an Android emulator. I followed the instructions in the React Native docs for installing Android Studio and setting the environment variables. I can create a default project with '''npx react-native init''' and run it without problems, so I guess my installation is fine. I cloned the repository, "npm installed" and got the following errors, trying to build fails as well. Since I am completely new to React Native and did not participate on this project so far I am clueless on how to approach this.

PS C:\Users\PP\pp-app> npm installnpm WARN aws-amplify-react-native@2.2.3 requires a peer of graphql@0.13.0 but none is installed. You must install peer dependencies yourself.npm WARN aws-amplify-react-native@2.2.3 requires a peer of react-native-fs@^2.12.1 but none is installed. You must install peer dependencies yourself.npm WARN aws-amplify-react-native@2.2.3 requires a peer of react-native-sound@^0.10.9 but none is installed. You must install peer dependencies yourself.npm WARN aws-amplify-react-native@2.2.3 requires a peer of react-native-voice@^0.2.6 but none is installed. You must install peer dependencies yourself.npm WARN eslint-plugin-react@7.12.4 requires a peer of eslint@^3.0.0 || ^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.npm WARN eslint-plugin-react-native@3.6.0 requires a peer of eslint@^3.17.0 || ^4 || ^5 but none is installed. You must install peer dependencies yourself.npm WARN react-native-elements@0.19.1 requires a peer of react-native-vector-icons@^4.2.0 but none is installed. You must install peer dependencies yourself.npm WARN react-native-qrcode-scanner@1.2.3 requires a peer of react-native-camera@^1.0.2 but none is installed. You must install peer dependencies yourself.audited 953593 packages in 10.847sfound 40843 vulnerabilities (39913 low, 930 moderate)  run `npm audit fix` to fix them, or `npm audit` for details
PS C:\Users\PP\pp-app> npx react-native run-androiderror React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:  - amazon-cognito-identity-js (to unlink run: "react-native unlink amazon-cognito-identity-js")  - react-native-camera (to unlink run: "react-native unlink react-native-camera")  - react-native-linear-gradient (to unlink run: "react-native unlink react-native-linear-gradient")  - react-native-vector-icons (to unlink run: "react-native unlink react-native-vector-icons")  - react-native-webview (to unlink run: "react-native unlink react-native-webview")This is likely happening when upgrading React Native from below 0.60 to 0.60 or above. Going forward, you can unlink this dependency via "react-native unlink <dependency>" and it will be included in your app automatically. If a library isn't compatible with autolinking, disregard this message and notify the library maintainers.Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.mdinfo Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.Jetifier found 1054 file(s) to forward-jetify. Using 8 workers...info Starting JS server...info Installing the app...Downloading https://services.gradle.org/distributions/gradle-4.10.1-all.zip...............................................................................................................Welcome to Gradle 4.10.1!Here are the highlights of this release: - Incremental Java compilation by default - Periodic Gradle caches cleanup - Gradle Kotlin DSL 1.0-RC6 - Nested included builds - SNAPSHOT plugin versions in the `plugins {}` blockFor more details see https://docs.gradle.org/4.10.1/release-notes.htmlStarting a Gradle Daemon (subsequent builds will be faster)> Configure project :react-native-auth0WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'.It will be removed at the end of 2019.For more information, see https://d.android.com/r/tools/task-configuration-avoidance.To determine what is calling variant.getJavaCompile(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.> Transform okhttp-urlconnection.jar (com.squareup.okhttp3:okhttp-urlconnection:3.12.1) with JetifyTransformERROR: [TAG] Failed to resolve variable '${animal.sniffer.version}'ERROR: [TAG] Failed to resolve variable '${project.groupId}'ERROR: [TAG] Failed to resolve variable '${project.version}'ERROR: [TAG] Failed to resolve variable '${project.groupId}'ERROR: [TAG] Failed to resolve variable '${project.version}'ERROR: [TAG] Failed to resolve variable '${project.groupId}'ERROR: [TAG] Failed to resolve variable '${project.version}'ERROR: [TAG] Failed to resolve variable '${project.groupId}'ERROR: [TAG] Failed to resolve variable '${project.version}'> Task :@react-native-community_async-storage:compileDebugJavaWithJavac> Task :amazon-cognito-identity-js:compileDebugJavaWithJavac> Task :app:generateDebugBuildConfig FAILED66 actionable tasks: 56 executed, 10 up-to-datewarning: [options] source value 7 is obsolete and will be removed in a future releasewarning: [options] target value 7 is obsolete and will be removed in a future releasewarning: [options] To suppress warnings about obsolete options, use -Xlint:-options. 3 warningswarning: [options] source value 7 is obsolete and will be removed in a future releasewarning: [options] target value 7 is obsolete and will be removed in a future releasewarning: [options] To suppress warnings about obsolete options, use -Xlint:-options. 3 warningsFAILURE: Build failed with an exception.* What went wrong:java.io.IOException: Unable to delete directory C:\Users\PP\pp-app\android\app\build\generated\source\buildConfig\debug\com.> Unable to delete directory C:\Users\PP\pp-app\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. Run with --scan to get full insights.* Get more help at https://help.gradle.orgBUILD FAILED in 2m 33serror Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081warning: [options] source value 7 is obsolete and will be removed in a future releasewarning: [options] target value 7 is obsolete and will be removed in a future releasewarning: [options] To suppress warnings about obsolete options, use -Xlint:-options.warning: [options] source value 7 is obsolete and will be removed in a future releasewarning: [options] target value 7 is obsolete and will be removed in a future releasewarning: [options] To suppress warnings about obsolete options, use -Xlint:-options.3 warningsFAILURE: Build failed with an exception.* What went wrong:java.io.IOException: Unable to delete directory C:\Users\PP\pp-app\android\app\build\generated\source\buildConfig\debug\com.> Unable to delete directory C:\Users\PP\pp-app\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. Run with --scan to get full insights.* Get more help at https://help.gradle.orgBUILD FAILED in 2m 33s    at checkExecSyncError (child_process.js:629:11)    at execFileSync (child_process.js:647:13)    at runOnAllDevices (C:\Users\PP\pp-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:74:39)    at buildAndRun (C:\Users\PP\pp-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:158:41)    at then.result (C:\Users\PP\pp-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:125:12)    at process._tickCallback (internal/process/next_tick.js:68:7)

Error: constructor ModuleRegistryAdapter in class ModuleRegistryAdapter cannot be applied to given types, new ModuleRegistryAdapter()

$
0
0

Hello im getting the fallowing error on console:

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081/Users/user/Desktop/.../android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java:82: error: constructor ModuleRegistryAdapter in class ModuleRegistryAdapter cannot be applied to given types;      new ModuleRegistryAdapter(),      ^  required: ReactModuleRegistryProvider  found:    no arguments  reason: actual and formal argument lists differ in length1 errorFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':app:compileDebugJavaWithJavac'.> Compilation failed; see the compiler error output for details.* 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.

on android studio:

/Users/username/.../project_name/android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java:82: error: constructor ModuleRegistryAdapter in class ModuleRegistryAdapter cannot be applied to given types;      new ModuleRegistryAdapter(),      ^  required: ReactModuleRegistryProvider  found: no arguments  reason: actual and formal argument lists differ in length

"react-native": "~0.61.5","react-native-unimodules": "^0.9.1",

It seems a recent react-native-unimodules bug on android, any solutions?this is the same error:https://www.gitmemory.com/issue/unimodules/react-native-unimodules/58/530738183


Invisible recaptcha in Expo SDK 37

$
0
0

const phoneProvider = new firebase.auth.PhoneAuthProvider();            const verificationId = await phoneProvider.verifyPhoneNumber(              phoneNumber,              recaptchaVerifier.current            );            setVerificationId(verificationId);
Can we use without recaptchaVerifier.current

How to split a column in to two subrows in react native

$
0
0

i have react native ui like thisenter image description here

my jsx for a component is

<View style={styleSheet.appItemStyle}><View style={{flex:1}}><Image style={styleSheet.appItemImageContainer} source={{uri: 'data:image/png;base64,'+item.icon}}/></View><View style={{flex:3, flexWrap: 'wrap'}}><Text style={styleSheet.appItemTextStyle}>{item.appName}</Text><Text style={{fontSize: 12, color: "#000"}}>{item.packageName}</Text></View><View style={{flex:1, alignContent: "center"}}><Text style={{fontSize: 15, color:'orange'}} onPress="">COPY</Text></View></View>

the problem with this ui is , the package name of the app is shown in another app row, for example, in the picture gmail package name is shown in settings suggestion app name, how can i split a column in to two rows, so that my second text stay on the same row instead of new row? i want the element of list view similar to the below screenshot, i want the title and text to be on same row, how can i solve this problem? I have just placed two text elements in a single row, but they tend to appear on next row, why this happens?

enter image description here

Android Studio is building old version via Generate Signed bundle / APK

$
0
0

I am trying to build APK from Android studio 3.6.3 to test on the device as well as for publishing app on google play console, but I noticed, Its building APK with the old version, tried almost everything

By the way, the build is working fine on the built-in emulator, however, sometimes it's also building the old version but by removing the build folder it solves the problem.

build.gradle

// The old version name was 1.1defaultConfig {    applicationId "com.companyName"    minSdkVersion rootProject.ext.minSdkVersion    targetSdkVersion rootProject.ext.targetSdkVersion    versionCode 3    versionName "1.2"    missingDimensionStrategy 'react-native-camera', 'general'    multiDexEnabled true}

Versioning

► android: ./gradlew -version------------------------------------------------------------Gradle 5.6.4------------------------------------------------------------Build time:   2019-11-01 20:42:00 UTCRevision:     dd870424f9bd8e195d614dc14bb140f43c22da98Kotlin:       1.3.41Groovy:       2.5.4Ant:          Apache Ant(TM) version 1.9.14 compiled on March 12 2019JVM:          14.0.1 (Oracle Corporation 14.0.1+7)OS:           Mac OS X 10.14.6 x86_64

Tried solutions

  1. File > Invalidate cache/restart > Invalidate cache/restart
  2. Build > Clean project
  3. Run > Edit Configuration > app > general > before launch > Gradle-aware make

Please help, Thanks in advance

Can't seem to display image using require or uri on React Native! What am I doing wrong?

$
0
0

import React from 'react';import { StyleSheet, Text, View, TouchableOpacity, Button, Image} from 'react-native';

export default class MentePair extends React.Component { render(){ return(

</View>    )}

}I have even tried importing image and require method. It doesn't work!

Is there a way to navigate to a default screen (Profile) if the path name does not match a route that I define explicitly?

$
0
0

I have tried writing the config object for my react native app according to the react-navigation configuring links docs.

I defined a series of path --> route mappings including Chat:'feed' and Explore:'news'

My goal is for the app to default to the Profile screen when resolving https://example.com/someusername and pass 'someusername' as the id param. Similar to how https://instagram.com/apple maps directly to the profile screen for @apple's account.

const linking = {  prefixes: ['https://example.com', 'example://'],  config: {    Home: {      path: '',      screens: {        Chat: 'feed',        Explore: 'news',        Profile: ':id',      },    },  },}

I will not allow users to make accounts @feed, @news, etc. to avoid conflict. I also display "user not found" message if 'someusername' does not exist yet

Is there a correct way to do this config object? Or if I need to write custom getStateFromPath / getPathFromState functions, does anyone have an example?

Cannot add task 'wrapper' as a task with that name already exists

$
0
0

When installing 'react-native init AwesomeProject' I get this error when I run react-native run-android:

Could not determine java version from '11.0.1'.

A quick google suggests I need to update the distributionUrl in the Gradle-wrapper. Having done this I am faced with a new error:

Cannot add task 'wrapper' as a task with that name already exists.

It suggests the issue is in the file:

/AwesomeProject/android/build.gradle' line: 36

which looks like this

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

I've been back and forth trying to figure out what this does. It seems odd that something wouldn't work straight out of the box. Is anybody facing a similar issue?

react-native-video-controls Warning Animated: `useNativeDriver` was not specified. in React-Native 62.2

$
0
0

I am using react-native to develop the Android APP ,I am using react-native-video-controls in my app after upgrading React_native from 60.0 to 62.2 .

I am getting error
Warning Animated: useNativeDriver was not specified. in React-Native 62.2 for react-native-video-controls

import Video from 'react-native-video';import VideoPlayer from 'react-native-video-controls';<View style={{ width: "100%", height: '100%', backgroundColor: '#065535' }} ><VideoPlayer                      navigator={this.props.navigator}                      source={{ uri: "https://howtags.com/"+ items.file_Name }}                      style={{ width: '100%', height: '100%', top: 0, left: 0, bottom: 0, right: 0, position: "absolute" }}                      ref={(ref) => { this.player = ref }}                      resizeMode="cover"                      posterResizeMode="cover"                      fullscreen={true}                      onEnd={this.onEnd}                      onLoadStart={this.onLoadStart}                      onProgress={this.onProgress}                      paused={this.state.paused}                      onFullScreen={this.state.isFullScreen}                      volume={10}                    /></View>

I am getting this error only after upgrading to "react-native": "^0.62.2", If anyone know the solution please help me


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.

Detox - Could not initialize class DefaultKotlinSourceSetKt

$
0
0

I've followed the Detox guide for Android here to install on my react-native project - https://github.com/wix/Detox/blob/master/docs/Introduction.Android.md. But after running react-native run-android to build the app. I get the following error evaluating project :detox:

1: Task failed with an exception.-----------* Where:Build file 'C:\Users\brian\Documents\Projects\react-native-prototyping\node_modules\detox\android\detox\build.gradle' line: 2* What went wrong:A problem occurred evaluating project ':detox'.> Could not initialize class org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSetKt

I've looked in their issue tracker but didn't see a related issue. Looking at similar issues around Kotlin it seems it could be a conflict between my kotlin and gradle version. But I'm not sure how to determine the correct versions to use. I also did a ./gradlew clean in the android folder to no avail.

Question:

How can you resolve 'Could not initialize class ..sources.DefaultKotlinSourceSetKt' error?

Some details of my gradle and package setup are as follows:

"devDependencies": {"detox": "^16.5.0",    },

root build.gradle:

buildscript {    ext {        buildToolsVersion = "28.0.3"        minSdkVersion = 18        compileSdkVersion = 28        targetSdkVersion = 28        kotlinVersion = '1.3.0'    }    repositories {        google()        jcenter()    }    dependencies {        classpath("com.android.tools.build:gradle:3.5.2")        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}

app/build.gradle:

android {    compileSdkVersion rootProject.ext.compileSdkVersion    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    defaultConfig {        applicationId "com.testapp"        minSdkVersion rootProject.ext.minSdkVersion        compileSdkVersion rootProject.ext.compileSdkVersion        targetSdkVersion rootProject.ext.targetSdkVersion        // detox automated tests config        // This will later be used to control the test apk build type        testBuildType System.getProperty('testBuildType', 'debug')          testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'    }    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(System.getenv("KEYSTORE") ?: "keystore.jks")            storePassword System.getenv("KEYSTORE_PASSWORD")            keyAlias System.getenv("KEY_ALIAS")            keyPassword System.getenv("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.            signingConfig signingConfigs.release            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"            // Detox-specific additions to pro-guard            proguardFile "${rootProject.projectDir}/../node_modules/detox/android/detox/proguard-rules-app.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"    }dependencies {    implementation fileTree(dir: "libs", include: ["*.jar"])    //noinspection GradleDynamicVersion    implementation "com.facebook.react:react-native:+"  // From node_modules    if (enableHermes) {        def hermesPath = "../../node_modules/hermes-engine/android/";        debugImplementation files(hermesPath +"hermes-debug.aar")        releaseImplementation files(hermesPath +"hermes-release.aar")    } else {        implementation jscFlavor    }    androidTestImplementation(project(path: ":detox"))}

upgrading my project to react navigation v5

$
0
0

Am working on my first react native project and after I put in many hours building my react navigation (version 4) setup and working on the different screens and components I came across a material design library called react native paper which offers some really cool looking components that will make my app look better so I started by trying to add the bottom nav bar, but it didn't work so I looked around only to find out that it goes along with the react native navigation v5 so is there a way to use react native bottom nav bar component from react paper with the version 4 of react navigation?if not how can i convert all the code to the version 5 syntax ?

here is my app.js file :

import React from "react";import { StyleSheet, Text, View } from "react-native";import { createAppContainer, createSwitchNavigator } from "react-navigation";import { createStackNavigator } from "react-navigation-stack";import { createBottomTabNavigator } from "react-navigation-tabs";import AccountScreen from "./src/screens/AccountScreen";import SigninScreen from "./src/screens/SigninScreen";import SignupScreen from "./src/screens/SignupScreen";import TrackCreateScreen from "./src/screens/TrackCreateScreen";import MainScreen from "./src/screens/MainScreen";import ResultShowScreen from "./src/screens/ResultsShowScreen";import { Provider as AuthProvider } from "./src/context/AuthContext";import { setNavigator } from "./src/navigationRef";import ResolveAuthScreen from "./src/screens/ResolveAuthScreen";const switchNavigator = createSwitchNavigator({  ResolveAuth: ResolveAuthScreen,  loginFlow: createStackNavigator({    Signup: SignupScreen,    Signin: SigninScreen,  }),  mainFlow: createBottomTabNavigator({    trackListFlow: createStackNavigator({      Main: MainScreen, //  TrackList: TrackListScreen      ResultsShow: ResultShowScreen, // TrackDetail: TrackDetailScreen    }),    TrackCreate: TrackCreateScreen, // we dont need this one    Account: AccountScreen,  }),});const App = createAppContainer(switchNavigator);export default () => {  return (<AuthProvider><App        ref={(navigator) => {          setNavigator(navigator);        }}      /></AuthProvider>  );};

here is an expo link to the full app : https://expo.io/@souhaildq/enews_app

How to solve "File name too long" while uploading local Image to Firestore and Firebase Storage in React Native?

$
0
0

I'm trying to upload local images to Cloud Firestore and Firebase storage.

The PACKAGES I'm using are

Here's the 2 functions I'm using:

export const uploadPost = async (postImageUri) => {        return new Promise(async(res, rej) => {                const fs = RNFetchBlob.fs;                fs.readFile(postImageUri,'hello','base64')                .then(async (data) => {                    console.log('data from RNFetchBlob', data);                    const storageRef = storage().ref(`posts/images`).child(`${data}`);                    try {                        storageRef.putFile(data,{contentType: 'image/jpeg'})                        .on(                            storage.TaskEvent.STATE_CHANGED,                            snapshot => {                                console.log('snapshot', snapshot.state);                                console.log('progress', (snapshot.bytesTransferred)/(snapshot.totalBytes)*100);                                if(snapshot.state === storage.TaskState.SUCCESS){                                    console.log('SUCCESS')                                }                            },                            error => {                                console.log('Image upload error', error);                                rej(error)                            },                            () => {                                storageRef.getDownloadURL()                                .then((downLoadUri) => {                                    console.log('File available at: ', downLoadUri);                                    // addPostInfo                                    res(downLoadUri)                                })                            }                        )                    }catch{err => console.log(err) }                })        } )}export const addPostInfo = async (post) => {    console.log('post.postImageUri in addPostInfo', post.postImageUri.slice(10))    const remoteUri = await uploadPost(post.postImageUri);    return new Promise((res, rej) => {        firestore()        .collection('posts')        .add({            id: post.id,            createdAt: post.date,            description: post.description,            image: remoteUri,            location: post.checkin_location        })        .then(ref => {            console.log('Finish adding in addPostInfo', ref)            res(ref)        })        .catch(err => rej(err))    })}

And in the main screen, I directly send the image's path to the addPostInfo:

const _onSharingPost = () => {        const postCreated = {            id: 'alkdgjhfa;oiughaoghus',            postImageUri: postImageUri,            date: _getCurrentDate(),            description: postDescription,            checkin_location: checkInLocation        }        postActions.addPostInfo(postCreated);    }

The path is like this:

content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F58/ORIGINAL/NONE/image%2Fjpeg/950379202

ERROR

...base64 string --> File name too long

It got down to the SUCCESS part of the upLoadPost function but then still got error

I HAVE TRIED:

  • Change the path --> cut off the content://
  • Use XMLHttpRequest to send the blob to the upLoadPost to send that to the storage

As far as I know, the problem must be the base64 string converted from the image path. I know we need to change that to blob or something, but I don't know how. I can't find where this can be specified in rn-fetch-blob docs

PLEASE HELP ME

React Native: How to translate sticky header like the one in Whatsapp for Android?

$
0
0

I would like to create a sticky header like the one in Whatsapp for Android. My approach, listen to the scroll-event and move the header right away, is stuttering, the one in Whatsapp is very smooth. And all the bounces of the ScrollView are transfered to the header, which looks ugly. The ideal solution would be to move the header first and terminate the pan responder while moving, so that the underlying ScrollView become the responders of the touch event - but this is not possbile.

Have you any suggestions to make this perfect?

Here's what i tried so far. Using Animated.views with Animated.values does not have any effect.

class scrollHeader extends Component {    constructor(props) {        super(props);        this.state = {            scrollY: 0        };        this.lastY = 0;    }    handleScroll(e) {        let dy = e.nativeEvent.contentOffset.y - this.lastY;        let scrollY = this.state.scrollY + dy;        scrollY = Math.min(scrollY, 80);        scrollY = Math.max(scrollY, 0);        this.setState({            scrollY: scrollY        });        this.lastY = e.nativeEvent.contentOffset.y;    }  render() {        const s = StyleSheet.create({            container: {                flex: 1            },            menu: {                position: 'absolute',                height: 160,                top: this.state.scrollY * -1,                left: 0,                right: 0,                backgroundColor: '#075e55',                zIndex: 1,                paddingTop: 40            },            text: {                fontSize: 16,                padding: 20            },            content: {                paddingTop: 160            }        });    return (<View style={s.container}><StatusBar translucent backgroundColor={'#06544c'} /><View style={s.menu}><Text>{'Menu Header'}</Text></View><ScrollView style={s.content} onScroll={(e) => this.handleScroll(e)}><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text><Text>{'Test'}</Text></ScrollView></View>    );  }}
Viewing all 28468 articles
Browse latest View live


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