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

Error: could not connect to SMTP in react native

$
0
0

I am trying to implement an SMTP email send in react native. I tried the same steps explained in the link https://github.com/angelos3lex/react-native-smtp-mailer/. But all the time when I try to send the mail, an alert with an error message "Error: could not connect to SMTP" is showing.Initially, I created a new project and replaced the App.js with https://github.com/angelos3lex/react-native-smtp-mailer/blob/master/example/App.js. The relevant fields like port, server, to and from email address are modified with my details.

Since I am new to react native, I don't know where I went wrong. Can you please help me?


How to integrate OpenStreetMap into a react-native project?

$
0
0

I am trying to integrate OpenStreetMap into a React Native project. But I can't find any library or anything related to React Native in their GitHub account.

The only thing I can find relating to these to topics is the link below, in which there is no proper answer.

https://www.reddit.com/r/reactnative/comments/5fi6bg/how_to_add_openstreetmap_to_a_react_native_project/

But I heard once that Mapbox uses OpenStreetMap as their source. Mapbox suggests a good way to integrate it into a React Native project:

https://github.com/mapbox/react-native-mapbox-gl

Is there a way to integrate OpenStreetMap into a React Native projector is it the case there's not proper support for it yet.

How to return a new Bundle in react native when app resumes

$
0
0

I want to receive an Image path when the app resumes. I am new to react native and I don't know much java for android. I am receiving Image path when my app is not in the background, but I am not receiving the new image path when the app resumes,Here is the code in MainActivity.java

    package com.myN;import com.facebook.react.ReactActivity;//tryimport com.facebook.react.ReactActivityDelegate;import android.content.Intent;import android.os.Bundle;import android.net.Uri;import java.io.InputStream;import java.io.File;import android.database.Cursor;import android.provider.MediaStore;import com.facebook.react.ReactRootView; //change//trypublic class MainActivity extends ReactActivity {  private ReactRootView mReactRootView; //change  @Override  protected String getMainComponentName() {    return "myN";  }  //try @Override    protected ReactActivityDelegate createReactActivityDelegate() {        return new ReactActivityDelegate(this, getMainComponentName()) {            @Override            protected Bundle getLaunchOptions() {                Intent intent = MainActivity.this.getIntent();                Bundle bundle = new Bundle();                Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);                if (imageUri != null ) {                    bundle.putString("image", imageUri.toString());                    return bundle;  //returning bunble containing image                 }else{                    bundle.putString("image", "");                    return bundle;                      }                }        };    }  //try  @Override  public Bundle onResume() {      super.onResume();           //what should be the code here to return new bundle which consist of new Image path  }}

This is the code in my Manifest file

<intent-filter><action android:name="android.intent.action.SEND" /><category android:name="android.intent.category.DEFAULT" /><data android:mimeType="image/*" /></intent-filter>

Now, when I share an image from the gallery, I am receiving the image prop with initial props (when the app starts) and can be accessed as this.props.image and I am getting this

content://com.android.providers.downloads.documents/document/38 

But the problem is, I am not receiving a new Image path when I again share an Image from the gallery (the rn app is background), I am receiving the same prop (same Image filePath when the app resumes) as before although I have shared a new Image with the rn app.I have read the documentation here, but I not able to understand where to write for the new props.

Splash screen GIF in react native

$
0
0

I am making an application with react native with native code of android and ios, in the application specifications a splash screen with a GiF is required, I have already inserted the required dependencies of the documentation of react native

dependencies {  // If your app supports Android versions before Ice Cream Sandwich (API level 14)  implementation 'com.facebook.fresco:animated-base-support:1.3.0'  // For animated GIF support  implementation 'com.facebook.fresco:animated-gif:2.0.0'  // For WebP support, including animated WebP  implementation 'com.facebook.fresco:animated-webp:2.1.0'  implementation 'com.facebook.fresco:webpsupport:2.0.0'  // For WebP support, without animations  implementation 'com.facebook.fresco:webpsupport:2.0.0'}

GIF support works correctly within the screen / components. However, when I try to place the GIF on the splash screen it doesn't work, there is a static image of the GIF

import android.content.Intent;import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;public class SplashActivity extends AppCompatActivity {     @Override        protected void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            Intent intent = new Intent(SplashActivity.this, MainActivity.class);            startActivity(intent);            finish();        }}<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"><item><bitmap                    android:gravity="center"                    android:src="@drawable/splash_screen2"/></item></layer-list>

How can I place a splash screen in gif format?

How to set Refresh Indicator of FlatList in react native?

$
0
0

I'm trying to set the refresh indicator of flat list in react native but don't know how to do it. List View has this prop :

refreshControl={<RefreshControl                        colors={["#9Bd35A", "#689F38"]}                        refreshing={this.props.refreshing}                        onRefresh={this._onRefresh.bind(this)}                    />                }

But Flat List has only these :

refreshing={this.props.loading}onRefresh={this._onRefresh.bind(this)}

React Native Expo upload image from android not working

$
0
0

I am trying to upload images from my phone which is perfectly working in iOS but it failed to work in android, have tried several android devices and all could not upload image to server. Have tried all various methods that I could find in web but none is working, wondering is it a problem with my code, expo, RN or android?

React native Upload.js

import React from 'react';import {    ActionSheetIOS,    Text,    View,    Platform,    Image,    TouchableOpacity} from 'react-native';import { ImagePicker } from 'expo';import { ActionSheetProvider, connectActionSheet } from '@expo/react-native-action-sheet';export default class TestUpload extends React.Component {    render() {        return(<ActionSheetProvider><TestUploadApp /></ActionSheetProvider>        );    }}@connectActionSheetclass TestUploadApp extends React.Component {    constructor(props) {        super(props)        this.state = {            imageSource: null,            imageUri: '',            imageName: '',            imageType: ''        }    }    async getPermissionAsync() {        const { CAMERA_ROLL, Permissions } = Expo;        try {            const status = await Permissions.askAsync(Permissions.CAMERA_ROLL);            return(status);        } catch(e) {            console.log(e);        }        if (status === 'granted') {            return CAMERA_ROLL.getCurrentPositionAsync({enableHighAccuracy: true});        } else {            throw new Error('Camera Roll permission not granted');        }    }    async getPermissionCamera() {        const { CAMERA, Permissions } = Expo;        try {            const status = await Permissions.askAsync(Permissions.CAMERA);            return(status);        } catch(e) {            console.log(e);        }        if (status === 'granted') {            return CAMERA.getCurrentPositionAsync({enableHighAccuracy: true});        } else {            throw new Error('Camera permission not granted');        }    }    componentDidMount() {        this.getPermissionAsync();        this.getPermissionCamera();    }    _PickImage = async() => {        let result = await ImagePicker.launchImageLibraryAsync({            allowsEditing: true,            aspect: [4, 4]        });        console.log(result);        if(!result.cancelled) {            let localUri = result.uri;            let filename = localUri.split('/').pop();            // Infer the type of the image            let match = /\.(\w+)$/.exec(filename);            let type = match ? `image/${match[1]}` : `image`;            let source = { uri: result.uri };            this.setState({                 imageSource: source,                imageUri: localUri,                imageName: filename,                imageType: type            });        }    }    _PickCamera = async() => {        let result = await ImagePicker.launchCameraAsync({            allowsEditing: true,            aspect: [4, 4]        });        console.log(result);        if(!result.cancelled) {            let localUri = result.uri;            let filename = localUri.split('/').pop();            // Infer the type of the image            let match = /\.(\w+)$/.exec(filename);            let type = match ? `image/${match[1]}` : `image`;            let source = { uri: result.uri };            this.setState({                 imageSource: source,                imageUri: localUri,                imageName: filename,                imageType: type            });        }    }    _ShowActionSheet = () => {        if(Platform.OS === 'ios') {            ActionSheetIOS.showActionSheetWithOptions({                options: ['Cancel', 'Take Photo', 'Choose From Gallery'],                cancelButtonIndex: 0,            },            (buttonIndex) => {                if(buttonIndex === 1) {                    this._PickCamera();                } else if (buttonIndex === 2) {                     this._PickImage();                }            });        } else if(Platform.OS === 'android') {            let options = ['Choose From Gallery', 'Take Photo', 'Cancel'];            let cancelButtonIndex = 2;            this.props.showActionSheetWithOptions({                options,                cancelButtonIndex,            },            (buttonIndex) => {                if(buttonIndex === 0) {                    this._PickImage();                } else if (buttonIndex === 1) {                     this._PickCamera();                }            });        }    }    SignUpProfile = () => {        const { imageUri, imageName, imageType } = this.state;        if(imageUri != null && imageUri != '') {            // Upload Image            let formData = new FormData();            formData.append('photo', {                uri: imageUri,                type: imageType,                name: imageName,            });            console.log(formData);            fetch(`${global.api}data_controller/signup_profile_upload_photo`, {                method: 'POST',                body: formData,                header: {'Content-Type': 'multipart/form-data'                }            }).then((response) => response.json())            .then((responseJson) => {                console.log(responseJson);            }).catch((error) => {                console.error(error);            });        }    }    render() {        return(<View><TouchableOpacity                    onPress={this._ShowActionSheet}><Image                         style={{                            width: 100,                            height: 100,                        }}                        source={this.state.imageSource != null ? this.state.imageSource : require('../../assets/images/tempat_ibadah.jpg')}                    /></TouchableOpacity><TouchableOpacity                    onPress={ this.SignUpProfile }><Text>Upload</Text></TouchableOpacity></View>        );    }}

Backend PHP upload-photo.php

/* I am using CodeIgniter 3.1.5 * In this case I have tried several methods */public function signup_profile_upload_photo() {    /* Method 1 using CI upload library */    /* Failed to upload in iOS and android */    $dir = './tmp';    if(!is_dir($dir)) {        if(mkdir($dir, 0777, TRUE)) {            $index = '<!DOCTYPE HTML><html><head><title>403 Forbidden</title></head><body><p>Directory access is forbidden.</p></body></html>';            write_file($dir . "/index.html", $index);        }    }    $config['upload_path'] = $dir;    $config['allowed_types'] = 'gif|jpg|png';    $this->load->library('upload', $config);    if($this->upload->do_upload('photo')) {        $callback['success'] = '1';    } else {        $callback['success'] = '0';    }    /* End of Method 1 */    /* Method 2, work perfectly in iOS, but not working in all android devices */    if(move_uploaded_file($_FILES['photo']['tmp_name'], './tmp/photo.jpg')) {        $callback['move'] = '1';    } else {        $callback['move'] = '0';    }    $data = json_encode($callback);    echo $data;}

When I console.log my FormData in react native, the result are as follows:

/* Android *//* When selecting image */Object {"cancelled": false,"height": 3120,"type": "image","uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540username%252Fprojectname/ImagePicker/538f376d-9a8c-4c4b-bc7f-bf3796785cec.jpg","width": 3120,}/* After appending to FormDataFormData {"_parts": Array [    Array ["photo",      Object {"name": "538f376d-9a8c-4c4b-bc7f-bf3796785cec.jpg","type": "image/jpg","uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540username%252Fprojectname/ImagePicker/538f376d-9a8c-4c4b-bc7f-bf3796785cec.jpg",      },    ],  ],}/* iOS *//* Selecting image */Object {"cancelled": false,"height": 1125,"type": "image","uri": "file:///var/mobile/Containers/Data/Application/200DE4DB-AD0D-40A2-9BF6-4C25B147B5B1/Library/Caches/ExponentExperienceData/%2540username%252Fprojectname/ImagePicker/1772B1F0-32EF-4212-8D56-374AD57535B9.png","width": 1122,}/* FormData */FormData {"_parts": Array [    Array ["photo",      Object {"name": "1772B1F0-32EF-4212-8D56-374AD57535B9.png","type": "image/png","uri": "file:///var/mobile/Containers/Data/Application/200DE4DB-AD0D-40A2-9BF6-4C25B147B5B1/Library/Caches/ExponentExperienceData/%2540username%252Fprojectname/ImagePicker/1772B1F0-32EF-4212-8D56-374AD57535B9.png",      },    ],  ],}

When I tried to console.log $_FILES['photo']['tmp_name'] after uploading with iOS, it does return a value "C:/xampp/tmp/file", but when trying to console.log the file after uploading with android, it does not return any value.

Thank you all in advance

could not reach cloud firestore backend with firestore emulator on android emulator

$
0
0

My problem is that I'm unable to call firestore from the client using the firebase firestore emulator on Android emulators. I've tested multiple Android emulators.

The error I'm getting suggests the app is unable to connect to firestore at all claiming there's not internet connection. Here's the full message: "@firebase/firestore:, Firestore (7.8.1): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=unavailable]: The operation could not be completedThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend."

This confuses me because my app works with the firebase firestore emulator on iOS. It also still works with the firebase cloud functions emulator for android. In case it matters, the app also works fine on iOS and Android when using firestore in production.

I'm creating a React Native app using the Expo managed workflow so I'm using firebase's web SDK. This means I'd have to eject to switch to react-native-firebase.

I've also looked at the docs and I seem to be following the instructions there: https://firebase.google.com/docs/emulator-suite/connect_firestore#web

I also came across this issue and I'm not clear if they're related. https://github.com/firebase/firebase-js-sdk/issues/2923 If they are I'm also not sure how I could fix it while remaining on the expo managed workflow.

Here's my firebase config

firebaseConfig.js

import * as firebase from 'firebase';// Optionally import the services that you want to use//import "firebase/auth";//import "firebase/database";import "firebase/firestore"; // uncommented so I could test locally w/ emulatorimport "firebase/functions";//import "firebase/storage";// ios id   // appId: "1:586841249272:ios:d8b508f7811d7c84e0b20d",// Initialize Firebaseconst firebaseConfig = {  apiKey: "AIzaSyAPybfM6EGsG0FOUj1UJ6udQ2BOzk9cZ_c",  authDomain: "fsp2-a670d.firebaseapp.com",  databaseURL: "https://fsp2-a670d.firebaseio.com",  projectId: "fsp2-a670d",  storageBucket: "fsp2-a670d.appspot.com",  messagingSenderId: "586841249272",  appId: "1:586841249272:android:fa68525699ea5cdde0b20d"};// added .firestore to test firestore locally w/ emulator const db = firebase.initializeApp(firebaseConfig).firestore(); // for debuggingfirebase.firestore.setLogLevel('debug')// Uncomment the below line to use cloud functions with the emulatorfirebase.functions().useFunctionsEmulator('http://localhost:5001')// firebase.firestore().settings({ experimentalForceLongPolling: true });// uncomment this to test firestore locally w/ emulator   db.settings({    host: "localhost:8080",    ssl: false  });

And here's the code in the file where the call to firestore from the client fails. It does

const More = ({navigation}) => {  const [userInfo, setUserInfo] = useState({profilePicture: 'placeholder', userName: ''});  useEffect(() => {    const changeUserInfo = async () => {      const userData = await new Promise(function (resolve, reject) {        // 2 - Copy-paste your code inside this function        firebase.auth().onAuthStateChanged(user => {          resolve(user) // this promise is rejected and I need to write the code to handle rejections        })      })      const db = firebase.firestore();      const uid = userData?.uid;      if (uid) {        const userRef = await db.collection('users').doc(uid);        const user = await userRef.get();        const userFields = user.data();        console.log('userFields is: ', userFields);        const {profilePicture, userName} = userFields;        console.log('profilePicture is: ', profilePicture);        console.log('userName is: ', userName);        setUserInfo(() => {          return {            profilePicture,            userName,          }        });      }    }    changeUserInfo()  }, [userInfo.profilePicture, userInfo.userName]

I'd really appreciate any help!

Change background of Android 10 home button area?

$
0
0

I'd like to change the background color of the area that has the home handle on Android 10. My app is built with React Native, if there is a way to do it with some package through that, that would be great. I would also be happy with knowing what to change in the android project files to change the color too. Here is a picture of what I mean:

Picture of android handle on Android 10

Please help! Thanks.


Decompile React Native index.android.bundle

$
0
0

I am using React Native and integrated library react-native-obfuscating-transformerto obfuscate my code. Now after decompiling my APK, I believe my whole js code is under assets/index.android.bundle.

How can I debundle it and see my code whether obfuscation worked or not.

Cant find the name of the Android's small dialog box component and how to implement it on React Native?

$
0
0

I want to recreate this small and discrete dialog box on the image below using React Native. I can find this component when I set an Alarm or copy some text to clipboard on my Android Phone. But I couldn't discover its name to start some research.

clock app showing a small and discrete dialog box

Where is AsyncStorage Data Physically Located on Android Devices?

$
0
0

Maybe the title isn't very clear. Here is what I mean/need to know-

If I use SQLite for some data storing purpose on Android app, I can see the DB created in my phone. (/root/data or something I guess). I have viewed the DB and performed some manipulations, it helps in development.

Now, I am using AsyncStorage API of react native.There is some problem in my code, I am not able to get the stored data from the store. Not sure what I am doing wrong.

So, to see what's wrong, is there a way to view the list of Objects that are being stored on the phone? If so where? And how do I view it?

PS: I am debugging my React Native app using Android Studio's logs. As my chrome on linux is a bad boy(Any Help would be appreciated)!

React-Native :java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so

$
0
0

I have just updated my project to use react-native version 0.60.2 . But when I am trying to run an application on Android device it gets crashed after launch screen. I got the following error logs :

E/AndroidRuntime: FATAL EXCEPTION: create_react_context    Process: com.tjspeed, PID: 3909    java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so        at com.facebook.soloader.SoLoader.doLoadLibraryBySoName(SoLoader.java:738)        at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:591)        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:529)        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:484)        at com.facebook.hermes.reactexecutor.HermesExecutor.<clinit>(HermesExecutor.java:20)        at com.facebook.hermes.reactexecutor.HermesExecutorFactory.create(HermesExecutorFactory.java:27)        at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:949)        at java.lang.Thread.run(Thread.java:760)

Few suggestions available here : https://github.com/facebook/react-native/issues/25601 but unfortunately none of them worked for me. Please suggest the workaround.

Error while merging dex archives: Program type already present: org.apache.commons.io.Charsets

$
0
0

I'm trying to release APK in react native using ./gradlew bundleRelease I tried

  • Cleaning gradle
  • Adding multiDexEnabled true

FAILURE: Build failed with an exception.

  • What went wrong: Execution failed for task ':app:transformDexArchiveWithDexMergerForRelease'.com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException:com.android.builder.dexing.DexArchiveMergerException: Error whilemerging dex archives: Program type already present:org.apache.commons.io.Charsets Learn how to resolve the issue athttps://developer.android.com/studio/build/dependencies#duplicate_classes.

This is my build.gradle

buildscript {    ext {        buildToolsVersion = "28.0.3"        minSdkVersion = 23        compileSdkVersion = 28        targetSdkVersion = 28        supportLibVersion = "28.0.0"        googlePlayServicesVersion = "11+"    }    repositories {        google()        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:3.4.2'        classpath 'com.google.gms:google-services:4.3.3'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        google()        mavenLocal()        jcenter()        maven {            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm            url "$rootDir/../node_modules/react-native/android"        }        maven {            // Android JSC is installed from npm            url("$rootDir/../node_modules/jsc-android/dist")        }    }}

app/build.gradle

apply plugin: "com.android.application"import com.android.build.OutputFileproject.ext.react = [    entryFile: "index.js",    enableHermes: false]apply from: '../../node_modules/react-native-unimodules/gradle.groovy'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 = falseandroid {    compileSdkVersion rootProject.ext.compileSdkVersion    buildToolsVersion rootProject.ext.buildToolsVersion    defaultConfig {        applicationId "com.package..."        minSdkVersion 23        targetSdkVersion rootProject.ext.targetSdkVersion        versionCode 33        versionName "33.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 {        release {            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {                storeFile file(MYAPP_UPLOAD_STORE_FILE)                storePassword MYAPP_UPLOAD_STORE_PASSWORD                keyAlias MYAPP_UPLOAD_KEY_ALIAS                keyPassword MYAPP_UPLOAD_KEY_PASSWORD            }        }    }    buildTypes {        release {            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:            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits            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            }        }    }    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    packagingOptions {       pickFirst '**/libjsc.so'       pickFirst 'lib/x86/libc++_shared.so'       pickFirst 'lib/x86_64/libjsc.so'       pickFirst 'lib/arm64-v8a/libjsc.so'       pickFirst 'lib/arm64-v8a/libc++_shared.so'       pickFirst 'lib/x86_64/libc++_shared.so'       pickFirst 'lib/armeabi-v7a/libc++_shared.so'    }}def jscFlavor = 'org.webkit:android-jsc:+'def enableHermes = project.ext.react.get("enableHermes", false);dependencies {    implementation fileTree(dir: "libs", include: ["*.jar"])    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"    implementation "com.facebook.react:react-native:+"  // From node_modules    implementation "com.google.android.gms:play-services-gcm:17.0.0"    implementation "com.google.android.gms:play-services-location:17.0.0"    //Add these lines    implementation "com.google.android.gms:play-services-base:17.3.0"    //implementation "com.google.firebase:firebase-core:15.0.2"    implementation "com.google.firebase:firebase-messaging:20.2.1"    implementation "com.google.firebase:firebase-inappmessaging:19.0.7"    // implementation "com.google.firebase:firebase-inappmessaging-display:19.0.7"    //implementation 'com.android.support:multidex:1.0.3'    //implementation project(':@mauron85_react-native-background-geolocation')    addUnimodulesDependencies()    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'

Still failing but on my emulator and android device its working fine. Does anyone have this problem too? I really appreciate any idea thanks.

How to create a video playing thumbnail area in react native?

$
0
0

Problem:

In my react native application in there I have an integrated camera application. What I want is when a user records a video I want to show the video to the user in a view before uploading it to the server. So I used a react-native-native-video package like this.

import React from 'react';import {View, Image, TouchableOpacity} from 'react-native';import AppText from '_components/appText';import Video from 'react-native-video';const navigateToCameraView = (navigation) => {  navigation.navigate('videorecording');};const VideoPreview = (props) => {  const {styles, navigation, fileName} = props;  return (<View style={styles.previewContainer}>      {fileName ? (<Video          source={{uri: fileName}} // Can be a URL or a local file.          // ref={(ref) => {          //   this.player = ref;          // }} // Store reference          // onBuffer={this.onBuffer} // Callback when remote video is buffering          // onError={this.videoError} // Callback when video cannot be loaded          style={styles.backgroundVideo}        />      ) : (<><TouchableOpacity onPress={() => navigateToCameraView(navigation)}><Image              source={require('_assets/img/cmerap.png')}              resizeMode="center"              style={styles.camPImage}            /></TouchableOpacity><AppText styles={styles.camPText}>Tap to capture video</AppText></>      )}</View>  );};export default VideoPreview;

But the issue is with this setup video cannot play when users click on the video.

I need a setup like this. It means I want a play button on the video and then I want to play the video when the user clicks on it.

enter image description here

But my code is showing a setup like this.

enter image description here

Can someone help me to solve this issue? Can someone suggest a way to for creating a preview video correctly using react-native? Thank you very much.

Why PanResponder is not working on android? What needs to be done for it to work on android devices?

$
0
0

Please help me out. I have spent many hours on this one. As a user touches the screen and move, I want to be able to draw lines on screen. PanResponder seems not to respond on android devices for achieving this functionality despite giving many thoughts. It works fine on iOS (I have tested on iOS simulator). How can I make it work on Android?

Snack: https://snack.expo.io/@harrysid98/ad4eb6

Code:

import React, { useRef, useState } from 'react';import { Dimensions, PanResponder, View, StyleSheet, Text, TouchableOpacity } from 'react-native';import Svg, { Polyline } from 'react-native-svg';const examplePath = [  { x: 90, y: 300 },  { x: 170, y: 45 },  { x: 250, y: 290 },  { x: 45, y: 130 },  { x: 285, y: 130 },  { x: 90, y: 298 }];const GesturePath = ({ path, color }) => {  const { width, height } = Dimensions.get('window');  const points = path.map(p => `${p.x},${p.y}`).join('');  return (<Svg height="100%" width="100%" viewBox={`0 0 ${width} ${height}`}><Polyline        points={points}        fill="none"        stroke={color}        strokeWidth="5"      /></Svg>      );};const GestureRecorder = ({ onPathChanged }) => {  const pathRef = useRef([]);  const panResponder = useRef(    PanResponder.create({      onMoveShouldSetPanResponder: () => true,      onPanResponderGrant: () => { pathRef.current = [] },      onPanResponderMove: (event) => {        pathRef.current.push({          x: event.nativeEvent.locationX,          y: event.nativeEvent.locationY,        })        onPathChanged([...pathRef.current]);      },      onPanResponderRelease: () => { onPathChanged([...pathRef.current]) }    })  ).current;  return (<View      style={[StyleSheet.absoluteFill, styles.container]}      {...panResponder.panHandlers}    />  );}const App = () => {  const [path, setPath] = useState(examplePath);  return (<View style={{flex: 1, borderWidth: 5, borderColor: 'pink', position: 'abolsute'}}><Text style={{bmarginBottom: 5}}>DUMMY TEXT</Text><GesturePath path={path} color="#33CCFF" /><View style={{borderWidth: 4, borderColor: 'pink',  position: 'absolute', marginTop: 100, marginLeft: 100}}><View><TouchableOpacity><Text>High</Text></TouchableOpacity><Text>High</Text><Text>High</Text><Text>High</Text></View></View><GestureRecorder onPathChanged={setPath} /></View>  );}const styles = StyleSheet.create({  container: {    backgroundColor: 'rgba(255,255,255,0.01)'  }})export default App

How do I read file with content-URI in React Native on Android?

$
0
0

I'm using React Native (0.48.3) for Android development. It seems, I'm stuck with a really trivial task: select a file and read it's content as a string. I have react-native-document-picker v2.0.0 for file selection, and it works fine: I can choose file and get it's URI. The problem is, I cannot make any package to read file with this link. I've already tried react-native-filesystem and react-native-fs, but it seems, they can work only with files in application directory. Anyway I get an error like this:

Error: File was not found: content://com.android.providers.downloads.documents/document/7

What package or function I need to use?

UPD: retrieving real, not content:// path, with react-native-get-real-path makes things work. But is this conversion really necessary, can one use content:// path for loading files?

Convert content:// URI to actual path for Android using React-Native

$
0
0

I am trying to upload images from cameraRoll. Thing is the cameraRoll component returns content:// URI rather than an actual file path. For uploading the image I need a file path, is there any way to convert content:// URI to file URI? Thanks

Components jiggle bug on Android in React Native app

$
0
0

Some of my components like modals, images, even just text is jiggling on Android in React Native app. And I can not find the cause of it. I checked and put just a typical component and anyway the the text inside of it is shaking:

export class XXX extends Component {  render() {    return (<ScrollView style={SS.container}><View><Text>This is </Text></View></ScrollView>    )  }}const SS = StyleSheet.create({  container: {    backgroundColor: 'red',    flex: 1,    width: '100%',    height: '100%',    alignItems: 'center',    justifyContent: 'center'  }})

If I delete flex: 1 the jiggle is stopped on text and images, but it is not working with modals, and is not possible to work without flex. This is my package.json:

{"name": "opencalls","version": "0.0.1","private": true,"scripts": {"start": "react-native start","test": "jest","postinstall": "npx jetify"  },"dependencies": {"@babel/core": "^7.6.2","@babel/runtime": "^7.6.2","@react-native-community/async-storage": "^1.5.1","@react-native-community/masked-view": "^0.1.10","@react-native-community/netinfo": "^5.3.3","@react-navigation/material-top-tabs": "^5.1.14","@react-navigation/native": "^5.4.2","@react-navigation/stack": "^5.2.18","base-64": "^0.1.0","fetch-intercept": "^2.3.1","lodash": "^4.17.15","mobx": "^5.15.4","mobx-react": "^6.2.2","moment": "^2.24.0","prop-types": "^15.7.2","react": "16.9.0","react-native": "^0.61.5","react-native-gesture-handler": "^1.6.1","react-native-keyboard-aware-scroll-view": "^0.5.0","react-native-keychain": "^6.0.0","react-native-material-menu": "^0.6.2","react-native-modal": "^4.1.0","react-native-paper": "^3.10.1","react-native-reanimated": "^1.8.0","react-native-safe-area-context": "^0.7.3","react-native-safe-area-view": "^1.1.1","react-native-screens": "^2.7.0","react-native-slider": "^0.11.0","react-native-sound": "^0.11.0","react-native-tab-view": "^2.14.0","react-native-user-avatar": "^1.0.7","react-native-vector-icons": "^6.6.0","save": "^2.3.3","validator": "^11.0.0"  },"devDependencies": {"@babel/plugin-proposal-decorators": "^7.8.3","babel-eslint": "^10.0.1","babel-jest": "^25.5.1","eslint": "6.0.1","eslint-config-airbnb": "^17.1.1","eslint-config-prettier": "^6.0.0","eslint-plugin-import": "^2.7.0","eslint-plugin-jsx-a11y": "^6.1.2","eslint-plugin-prettier": "^3.1.0","eslint-plugin-react": "^7.12.4","eslint-plugin-react-native": "^3.6.0","jest": "^25.5.4","jetifier": "^1.6.5","metro-react-native-babel-preset": "0.56.0","prettier": "^1.18.2","react-test-renderer": "16.9.0"  },"jest": {"preset": "react-native"  }}

And the video https://drive.google.com/file/d/1euwX6ND2D3YI-pCrO-mRTb6ySvJoRqN5/view?usp=sharing. Any ideas how can I solve it?

Task '$' not found in root project - problem in React-Native

$
0
0

The error im getting is:Task '$' not found in root project 'My-App'

Using gradle version 6.3, windows 10. other projects are running with no problems

This is the command im using:react-native run-android --variant=appDebug --appIdSuffix app(I changed the names in the command, but there are no problems with it)

Thanks in advance!

How to rename / move a folder in react native fs?

$
0
0

I am having trouble renaming and moving folders cause react native fs has only moveFile option that performs on files only and not folders.Doing it recursive is also messy and it is hard to execute lines after performing rename or move option due to synchronous execution.I have attached the code for move below with the bug.Kindly help me figure this out.

moveAll = (path, outputPath) => new Promise((resolve, reject) => {// is a folderif (path.split(".").length == 1) {  // CHeck if folder already exists  RNFS.exists(outputPath)    .then((exists) => {      if (exists) {        // Delete the folder if exists        RNFS.unlink(outputPath)          .then(() => {          })          // `unlink` will throw an error, if the item to unlink does not exist          .catch((err) => {            console.log(err.message);          });      }      // MAKE FRESH FOLDER      RNFS.mkdir(outputPath);      resolve(RNFS.readDir(path)        .then((result) => {          result.map(            (item) =>              new Promise((resolve, reject) => {                resolve(this.moveAll(item.path, outputPath +"/" + item.name));              })          )        })        .catch((e) => {          console.log("ERROR", e)        })      )    })    .catch((e) => {      console.log(e)    })} else {  RNFS.moveFile(path, outputPath)    .then(() => {    })    .catch((e) => {      console.log(e)    })}})

Thanks in advance :)

Viewing all 28482 articles
Browse latest View live