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

React Native background job at midnight

$
0
0

I was wondering if there is a way to run some Javascript code at midnight if the app is in background/foreground state and I found out there are some npm packages out there for React Native that lets you schedule background jobs that are executed at a set interval, but that wasn't what I was looking for so I decided to use the Headless Js API from React Native, but I couldn't get it to execute. I tried creating the service:

package com.backgroundspecificjob;import android.content.Intent;import android.os.Bundle;import com.facebook.react.HeadlessJsTaskService;import com.facebook.react.bridge.Arguments;import com.facebook.react.jstasks.HeadlessJsTaskConfig;import javax.annotation.Nullable;public class MidnightTask extends HeadlessJsTaskService {    @Override    protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {        Bundle extras = intent.getExtras();        if(extras != null) {            return new HeadlessJsTaskConfig("MidnightTask",                    Arguments.fromBundle(extras),                    5000            );        }        return null;    }}

then setting up a receiver:

package com.backgroundspecificjob;import android.app.ActivityManager;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;;import com.facebook.react.HeadlessJsTaskService;import java.util.List;public class MidnightReceiver extends BroadcastReceiver {    @Override    public void onReceive(final Context context, final Intent intent) {        final String action = intent.getAction();        if(!isAppOnForeground(context) && Intent.ACTION_DATE_CHANGED.equals(action)) {            Intent serviceIntent = new Intent(context, MidnightTask.class);            serviceIntent.putExtra("midnight", true);            context.startService(serviceIntent);            HeadlessJsTaskService.acquireWakeLockNow(context);        }    }    private boolean isAppOnForeground(Context context) {        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);        List<ActivityManager.RunningAppProcessInfo> appProcesses =                activityManager.getRunningAppProcesses();        if (appProcesses == null) {            return false;        }        final String packageName = context.getPackageName();        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {            if (appProcess.importance ==                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&                    appProcess.processName.equals(packageName)) {                return true;            }        }        return false;    }}

and at last setting an intent as well as the service in Androidmanifest.xml:

<service      android:name=".MidnightTask"     android:enabled="true"     android:exported="true"/><receiver             android:name=".MidnightReceiver"            android:enabled="true"            android:exported="true"><intent-filter><action android:name="android.intent.action.DATE_CHANGED" /></intent-filter></receiver>

But it seems that if I change the date to 23:59 and then wait for it to be 00:00 the intent is not triggered and furthermore the service is not called. I also registered the headless task in AppRegistry:

AppRegistry.registerHeadlessTask('MidnightTask', () =>  require('./onMidnightClear'),);

I can't get the code to work and I don't quite understand why this is not working. If anyone knows the solution to my problem please let me know :)


Unable to resolve module `./Linking/Linking` from `node_modules/expo/build/ExpoLazy.js`

$
0
0

Has anyone experience this error with expo, when running react-native run-android?

error: bundling failed: Error: Unable to resolve module `./Linking/Linking` from `node_modules/expo/build/ExpoLazy.js`: None of these files exist:  * node_modules/expo/build/Linking/Linking(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)  * node_modules/expo/build/Linking/Linking/index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)

"expo": "^37.0.9",

expo + react-native: There was a problem sending log messages

$
0
0

I am building a react-native app that I recently moved to expo. The app seems to display the expected screen, but before it completes, I am receiving the following error message: console.error: "There was a problem sending log messages to your development environment, {"name": "Error"}". When I view the expo browser screen I see the following stack trace when I click on the device:

  node_modules/expo/build/logs/LogSerialization.js:146:14 in _captureConsoleStackTrace  node_modules/expo/build/logs/LogSerialization.js:41:24 in Object.serializeLogDataAsync$  node_modules/regenerator-runtime/runtime.js:62:39 in tryCatch  node_modules/regenerator-runtime/runtime.js:288:21 in Generator.invoke [as _invoke]  node_modules/regenerator-runtime/runtime.js:114:20 in Generator.prototype.(anonymous  node_modules/regenerator-runtime/runtime.js:62:39 in tryCatch  node_modules/regenerator-runtime/runtime.js:152:19 in invoke  node_modules/regenerator-runtime/runtime.js:187:10 in <unknown>  node_modules/promise/setimmediate/core.js:45:4 in tryCallTwo  node_modules/promise/setimmediate/core.js:200:12 in doResolve

Here is a screenshot of the error:

enter image description here

What does this error mean? I found some doc referring to removing console.log statements and removed the ones I had but that did not help.

React Native react-native-music-metadata or any other library for reading id3 [closed]

$
0
0

trying to make music player app I decided to use "react native music metadata" to get song title, album cover etc. I have done everything following guide on:

https://www.npmjs.com/package/react-native-music-metadata

and got error:

Execution failed for task ':react-native-music-metadata:compileDebugJavaWithJavac'.

Maybe anyone know a good way to read id3 from mp3 file to read song info on react native (non expo).

Type Error: u.slice is not a function. in index.android.bundle when I try to run a simple React Native app on android simulator

$
0
0

So I followed this video to build a simple Shopping List app using React Native:https://youtu.be/Hf4MJH0jDb4

It runs fine when I use react-native run-ios to get it running on the iOS simulator(actually some problems too, but I'm working on it), but when I try to run it using react-native run-android, a lot of problems arise.

1st problem, when the app does come up, I try to add an item, but after I press the "Add Item" button, this Type Error: u.slice is not a function. shows up.

enter image description here

so, as the problem code comes from index.android.bundle, I go there, and I have absolutely no idea what I am looking at and what I should do about it to fix the problem.

In case it helps, this is the 157th line of code where the Type Error occurs, is like:

__d(function(g,r,i,a,m,e,d){'use strict';var t=r(d[0]),n=t(r(d[1])),o=t(r(d[2])),l=t(r(d[3])),s=t(r(d[4])),u=t(r(d[5])),c=(function(){function t(){(0,n.default)(this,t)}return(0,o.default)(t,null,[{key:"alert",value:function(n,o,u,c){if('ios'===l.default.OS)t.prompt(n,o,u,'default');else if('android'===l.default.OS){if(!s.default)return;var f=s.default.getConstants(),p={title:n||'',message:o||'',cancelable:!1};c&&c.cancelable&&(p.cancelable=c.cancelable);var v=u?u.slice(0,3):[{text:"OK"}],y=v.pop(),b=v.pop(),h=v.pop();h&&(p.buttonNeutral=h.text||''),b&&(p.buttonNegative=b.text||''),y&&(p.buttonPositive=y.text||"OK");s.default.showAlert(p,function(t){return console.warn(t)},function(t,n){t===f.buttonClicked?n===f.buttonNeutral?h.onPress&&h.onPress():n===f.buttonNegative?b.onPress&&b.onPress():n===f.buttonPositive&&y.onPress&&y.onPress():t===f.dismissed&&c&&c.onDismiss&&c.onDismiss()})}}},{key:"prompt",value:function(t,n,o){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:'plain-text',c=arguments.length>4?arguments[4]:void 0,f=arguments.length>5?arguments[5]:void 0;if('ios'===l.default.OS){if('function'==typeof s){console.warn("You passed a callback function as the \"type\" argument to Alert.prompt(). React Native is assuming  you want to use the deprecated Alert.prompt(title, defaultValue, buttons, callback) signature. The current signature is Alert.prompt(title, message, callbackOrButtons, type, defaultValue, keyboardType) and the old syntax will be removed in a future version.");var p=s;return void u.default.alertWithArgs({title:t||'',type:'plain-text',defaultValue:n||''},function(t,n){p(n)})}var v,y,b=[],h=[];'function'==typeof o?b=[o]:Array.isArray(o)&&o.forEach(function(t,n){if(b[n]=t.onPress,'cancel'===t.style?v=String(n):'destructive'===t.style&&(y=String(n)),t.text||n<(o||[]).length-1){var l={};l[n]=t.text||'',h.push(l)}}),u.default.alertWithArgs({title:t||'',message:n||void 0,buttons:h,type:s||void 0,defaultValue:c,cancelButtonKey:v,destructiveButtonKey:y,keyboardType:f},function(t,n){var o=b[t];o&&o(n)})}}}]),t})();m.exports=c},151,[1,26,27,50,152,153]);

And when I try to reload the app, it says Could not connect to development server, although it still runs on iOS simulator perfectly fine.

enter image description here

I am absolutely a beginner on mobile app development and React Native, so there are a lot of things I don't know, and just trying to run the apps on simulators have caused me a lot of headaches.

Thank you in advance.

Show photo taken with React Native Image Picker

$
0
0

I'm learning a little bit about React Native and a question came up that I couldn't solve.

I'm using react-native-image-picker I have been able to take a photo from my device, the problem is that I cannot show the captured image on the device screen.

Here is my code.

import React from 'react';import { Button, Image, View} from 'react-native';import ImagePicker from 'react-native-image-picker';const TomarFoto = () => {  const tomarFoto = () => {    ImagePicker.launchCamera({}, (response) => {      console.log('Respuesta =', response);      if (response.didCancel) {        alert('Subida cancelada');      } else if (response.error) {        alert('Error encontrado: ', error);      } else {        const source = {uri:response.uri};      }    });  }; return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Image      source={ uri:response.uri}      style={ { width: 300, height: 300 } }    /><Button title="Adjuntar foto" onPress={tomarFoto} /></View> ); };export default TomarFoto;

When I take the picture and I'm on Debug Mode, the data I obtain is:

Respuesta = {height: 3000, fileSize: 538811, data: "/9j/4R7KRXhpZgAATU0AKgAAAAgACgEQAAIAAAANAAAAhgExAA…BTmj2jnrRRQBXkwD1oGKKKAHA47CgsOlFFADJGxRRRTsB/9k=", path: "/storage/emulated/0/Pictures/image-bf1edaf0-350f-40d6-b1c3-cccc125e1368.jpg", uri: "content://com.sinvirus.provider/root/storage/emula…es/image-bf1edaf0-350f-40d6-b1c3-cccc125e1368.jpg",…}data: "/9j/4R7KRXhpZgAATU0AKgAAAAgACgEQAAIAAAANAAAAhgExAA"fileName: "image-bf1edaf0-350f-40d6-b1c3-cccc125e1368.jpg"fileSize: 538811height: 3000isVertical: truelatitude:  longitude: originalRotation: 0path: "/storage/emulated/0/Pictures/image-bf1edaf0-350f-40d6-b1c3-cccc125e1368.jpg"timestamp: "2020-05-10T23:21:29Z"type: "image/jpeg"uri: "content://com.sinvirus.provider/root/storage/emulated/0/Pictures/image-bf1edaf0-350f-40d6-b1c3-cccc125e1368.jpg"width: 3000__proto__: Object

But here is my problem, I want to show that photo into the View but everytime i get this error Message, enter image description here

Any Idea how could I fix this or what I'm doing wrong?

How to test npm library having native dependecy

$
0
0

I am new to the world of testing.

I have react-native-formly npm library written entirely in javascript but have a component or two which are dependent on native libraries like react-native-image-picker.

Recently, I updated all my dependencies thinking it won't cause any breaking changes but it turned out it actually did.

My primary goal here is to write test cases for the component which require native implementation (test case as simple as app doesn't crash on initialising my component).

Flutter Device Preview equivalent in React Native App?

$
0
0

recently i've found this plugin can preview many device of Android or iOS device in one installed apps,

gif of the plugin is at https://github.com/aloisdeniel/flutter_device_preview

enter image description here

does react native has something like this?

I know there's some similar plugin like Expo and Appetize but i need something like this,

i mean i can preview of many device in my apps, not installing my app on many devices.


Having trouble navigating screen to screen. React Native

$
0
0

Not able to navigate within screens. I'm building an app on visual studio code with Android studio. Please tell me if I'm missing something. Getting error: Unable to resolve "./views/Header/Header" from "node_modules\react-navigation-stack\lib\module\index.js"What am i doing wrong?I need help please. Thanks

App.js

```import React from 'react';import { StyleSheet, Text, View, StatusBar, Platform, YellowBox} from 'react-native';import Register from './app/components/Register';import Login from './app/components/Login';import MenteApr from './app/components/MenteApr';import { createStackNavigator } from 'react-navigation-stack';const Navigator = createStackNavigator( {        initialRouteName: 'Register',      },  {    Register: {      screen: Register    },     Login: {      screen: Login,    },    MenteApr: {      screen: MenteApr,      },        }    );export default class App extends React.Component {  render(){  return <Navigator />;}}```This is the register file **Register.js**```import React from 'react';import {     StyleSheet,     Text,     View,    TextInput,    TouchableOpacity,    Image,    Button} from 'react-native';export default class Register extends React.Component {  static navigationOptions = {    title: 'Register',  };  render(){  return(<View style={styles.register}><Text> Welcome to MentorMe</Text><Text> Sign Up </Text><TextInput} placeholder = "Student ID"        underlineColorAndroid= {'transparent'} /><Button         title = "Register"         onPress={()=>            this.props.navigation.push('MenteApr')  }           /><View ><Text> Already have an account? </Text><Button           title  = "Login"          onPress={()=>            this.props.navigation.navigate('Login') }         /></View></View>  );}}const styles = StyleSheet.create({  register: {    alignSelf: 'stretch',    flex: 1,    justifyContent: 'center',    backgroundColor: '#36485f',    paddingLeft: 60,    paddingRight: 60,  }```This is the Login file **Login.js**import React from 'react';import {     StyleSheet,     Text,     View,    TextInput,    TouchableOpacity,    Button} from 'react-native';export default class Login extends React.Component {static navigationOptions ={    title: "Login",  };  render(){  return(<View style = {styles.login}><Text> Welcome Back!</Text><TextInput placeholder = "Student ID"        underlineColorAndroid={'transparent'} /><Button           title="Login"          onPress ={() =>            this.props.navigation.push('MenteApr')            } /><View><Text> Don't have an account? </Text><Button          title="Sign Up"          onPress ={() =>            this.props.navigation.navigate("Register")}         /></View></View>  );}}const styles = StyleSheet.create({    login: {      alignSelf: 'stretch',      flex: 1,      justifyContent: 'center',      backgroundColor: '#36485f',      paddingLeft: 60,      paddingRight: 60,    }

What is the difference between react-native cli and Expo with Bare workflow?

$
0
0

I am going to build a very big application with multiple complex functionalities. but I am stuck on bellow points -

  1. What is the difference between react-native cli and Expo with Bare workflow?
  2. what Should I include in my project and why?
  3. is Facebook created expo?

Android java.lang.UnsatisfiedLinkError: couldn't find DSO to load

$
0
0

I just set up a brand new react-native project (0.62). Running a fresh debug build works just fine.

I set up signing following the documentation: https://reactnative.dev/docs/signed-apk-android, and ensured that I'm using the following ABIs: "armeabi-v7a", "x86", "arm64-v8a", "x86_64".

To test out a release build, I run the following: npx react-native run-android --variant release

Problem

After running the above command, the app attempts to start and crashes immediately with the following stack trace:

    --------- beginning of crash2020-05-01 09:34:26.707 19961-19976/? E/AndroidRuntime: FATAL EXCEPTION: create_react_context    Process: <BUNDLE_ID>, PID: 19961    java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so        at com.facebook.soloader.SoLoader.doLoadLibraryBySoName(SoLoader.java:789)        at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:639)        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:577)        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:525)

Sure enough, when I unpackage the APK there is no libhermes.so in /lib/x86_64 (I am testing at the moment on pixel 2 API 28).

I'm not sure why hermes wasn't enabled to start out with, but just to be sure I set the following in my build.grade:

project.ext.react = [    enableHermes: true,  // clean and rebuild if changing]

Now after cleaning and building I do see libhermes.so. Unfortunately, I am still seeing the same exact issue. But I can see that the file exists.

At this point, I'm pretty stuck. I've followed a number of threads reporting the same issue (for example, this). It sounds like an underlying issue with soloader has been fixed and is being used with the latest version of react native. Although I'm using the latest version of RN, I'm still seeing this issue.

Question

Not being terribly familiar with Android development, what steps might I take to investigate this issue further?

React Native Text and Read More Component - Number of lines does not recognise new line

$
0
0

This is an Android issue only.

I am trying to use Read More component, so that the first text component is the header and the rest is hidden unless you click read more button:

<ReadMore      numberOfLines={1}      renderTruncatedFooter={handlePress => (<Text style={this.styles.readMoreButton} onPress={handlePress}>          {this.props.readMore}</Text>      )}      renderRevealedFooter={handlePress => (<Text style={this.styles.readMoreButton} onPress={handlePress}>          {this.props.showLess}</Text>      )}      textStyle={{        textAlign:'center'      }}><Text        style={{          fontFamily: 'RobotoMedium',          fontSize: 12,          textAlign: 'center',          color: this.props.color        }}>        {`${this.props.termsTitle} ${"\n"}`}</Text><Text style={this.styles.description}>{this.props.text}</Text></ReadMore>

However, the number of lines do not recognise the new line and this is how it looks like:

enter image description here

I would like to have Vilkar og betingelser on the top and then the rest of the text hidden.

On the other hand, when I open the text it works correctly:

enter image description here

Custom Alert control in react-native

$
0
0

I am developing react-native app and trying to make a custom alert method (like Alert. alert() as given in Official site of react-native). React-native alert has no styling property for Font Size and back-ground Color, alert is very small when i'm using on android tab but it's work fine while on using in android scanner and mobile.

enter code hereimport React, { Component } from 'react';import { StyleSheet, Platform, View, Text,TouchableOpacity } from 'react-native'; // import PropTypes from 'prop-types';// import Dialog from "react-native-dialog"; import Alertfunction from './src/CustomAlert' export default class App extends Component{    render() {      return (<Alertfunction Title={"Alert"} FontSize = {30} FontColor= '#FF9800'  Visible={true}/>      );    }  }const styles = StyleSheet.create({ MainContainer :{  flex:1,  paddingTop: (Platform.OS) === 'ios' ? 20 : 0,  alignItems: 'center',  justifyContent: 'center',  }});customAlert.jsimport React, { Component } from 'react';import { StyleSheet, Platform, View, Text,TouchableOpacity } from 'react-native'; import PropTypes from 'prop-types';import Dialog from "react-native-dialog";class Alertfunction extends Component {    state = {        dialogVisible: this.props.Visible      };      showDialog = () => {        this.setState({ dialogVisible: this.props.Visible });      };      handleCancel = () => {         this.setState({ dialogVisible: false });        // this.props.Visible=false;      };      handleDelete = () => {         this.setState({ dialogVisible: false });        //this.props.Visible=false;      };  render() {    return (<View><TouchableOpacity onPress={this.showDialog}><Text >{this.props.Title}</Text></TouchableOpacity><Dialog.Container visible={this.state.dialogVisible}><Dialog.Title style={{fontSize : this.props.FontSize, color: this.props.FontColor}}>{this.props.Title}</Dialog.Title><Dialog.Description style={{fontSize : this.props.FontSize, color: this.props.FontColor}}>                    Do you want to delete this account? You cannot undo this action.</Dialog.Description><Dialog.Button style={{fontSize : this.props.FontSize, color: this.props.FontColor}} label="Cancel" onPress={this.handleCancel} /><Dialog.Button style={{fontSize : this.props.FontSize, color: this.props.FontColor}} label="ok" onPress={this.handleDelete} /></Dialog.Container></View>    );  } }export default Alertfunction;Alertfunction.propTypes ={    Title: PropTypes.string,  FontSize: PropTypes.number,  FontColor: PropTypes.string,  Visible: PropTypes.bool,}Alertfunction.defaultProps ={    Title: "Default Name",  FontColor: "#00E676",  FontSize: 15,  Visible:false}const styles = StyleSheet.create({ MainContainer :{  flex:1,  paddingTop: (Platform.OS) === 'ios' ? 20 : 0,  alignItems: 'center',  justifyContent: 'center',  }});

react native place ui when bundle is being parsed

$
0
0

I want to know if it is possible to provide a custom UI when the js bundle is being initially parsed (the white screen we see on startup when the modules are being loaded).

Integrate Python OpenCV with React Native

$
0
0

I have an app built on React Native whose core functionality is to capture some images, analyse and process the images and return some results. As of now the image analysis was done in the server side using python and opencv. Only the results and the resultant images were returned. Now as per the requirement by the clients, due to privacy concerns, they want the image processing to be done on the mobile app itself. (As the images are medical related and they don't want the images to be sent to the server)

So, my question is, if there is a way I can use my existing python with opencv code and integrate it directly into react-native/android/ios?

Right now what I am doing is using the library react-native-opencv3 , numjs, etc to re-write the algorithm in react-native as I feel comfortable using javascript (I have no experience in swift). However not all opencv, numpy functions are supported by these libraries and it is consuming all the time to re-write the code.

I found about using jython, python-for-android and swift-python-interoperabilityCan I use these to directly integrate python opencv code into my current application? If yes, it would be great if someone can help me with some small example or guidelines as I cannot find anything.

Other method that I considered was:

Re-write the algorithm using native code and opencv-android and opencv-ios sdks and create the react-native bridge to call the algorithm. (I am guessing it will take a lot of time as I have to write in 2 different languages. Time that I don't have)


when using index.bundle.android app crashes

$
0
0

E/ReactNativeJS: TypeError: null is not an object (evaluating 't(r(d[1])).default.Direction')E/ReactNativeJS: Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules

When using index.bundle.android in library module ,android app crashes

$
0
0

Error:

E/ReactNativeJS: TypeError: null is not an object (evaluating 't(r(d[1])).default.Direction')E/ReactNativeJS: Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules Process: com.snapwork.map, PID: 9692 com.facebook.react.common.JavascriptException: TypeError: null is not an object (evaluating 't(r(d[1])).default.Direction'), stack: @481:133 v@2:1474 @473:810 v@2:1474 @472:241 v@2:1474 @471:313 v@2:1474 @467:280 v@2:1474 @466:190 v@2:1474 @459:2805 v@2:1474 @385:159 v@2:1474 @384:131 v@2:1474 @6:58 v@2:1474 d@2:876 global code@944:4

    at com.facebook.react.modules.core.ExceptionsManagerModule.reportException(ExceptionsManagerModule.java:79)    at java.lang.reflect.Method.invoke(Native Method)    at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)    at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:151)    at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)    at android.os.Handler.handleCallback(Handler.java:883)    at android.os.Handler.dispatchMessage(Handler.java:100)    at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)    at android.os.Looper.loop(Looper.java:227)    at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)    at java.lang.Thread.run(Thread.java:919)

When using bundle in library module than app crashes and gives above exception. Same is working in normal project.

React Native Post Request via Fetch throws Network Request Failed

$
0
0

I´ve came across the following error. At the moment I developing an Android App with React Native therefore I´m planning to use fetch for doing a post request for me.

fetch("https://XXreachable-domainXX.de/api/test", {            method: "post",            body: JSON.stringify({                param: 'param',                param1: 'param',            })        }    )        .then((response) = > response.json()    )    .    then((responseData) = > {        ToastAndroid.show("Response Body -> "+ JSON.stringify(responseData.message), ToastAndroid.SHORT    )})    .    catch((error) = > {        console.warn(error);})    ;

The app now throws an error:

TypeError: Network request failed

When I change the code to a GET-Request it´s working fine, in the browser with a window.alert() as a return it´s cool and also the chrome extension Postman returns data correctly.

React Native 0.57.x large images low quality

$
0
0

There is really low quality when loading large bundled images, even when using resizeMethod="resize". This happens only on Android, not on any iOS simulator/device. Have tested it on Android 8.1 emulator and LG G6 with Android 8.0. Please see the screenshots bellow.

At the left screenshot we see the exact same code running with RN 0.56.0 and at the right screenshot we see RN 0.57.5. The code is just a simple image <Image source={require('./assets/ELHall1.png')} resizeMethod="resize" /> and the image size is 2111 x 4645 pixels. Both projects are fresh installed using react-native init RN057ImageTest and react-native init --version="0.56.0" RN056ImageTest.

Simple App with an Image

...type Props = {};export default class App extends Component<Props> {  render() {    return (<View style={styles.container}>        {/*<Text style={styles.welcome}>Welcome to React Native!</Text><Text style={styles.instructions}>To get started, edit App.js</Text><Text style={styles.instructions}>{instructions}</Text>*/}<Image source={require('./assets/ELHall1.png')} resizeMethod="resize" /></View>    );  }}...

I have created a Github issue to RN repo since September but noone has replied which makes me think that I am doing something wrong. Is there a new prop or an other way to make large images show normal with full quality in RN 0.57.x? Maybe the metr obuilder updates to 0.57.x have changed how the bundler handles the image assets? I have used resizeMethod prop to "scale" and "resize" with no difference at all. I have used PNG8, PNG24 and PNG32 all same result.

EDIT

The Github repo with the code and the PNG image files: https://github.com/clytras/RN057ImageTest

Please don't give any answers about JPEG images and that they do work, I already know that; I want to make PNG images work like they do in RN 0.56.

UPDATE JAN/2020

This is an update for people landing here regarding this issue.

The RN Issue has been closed since August 10, 2019 with the statement that this is not a React Native issue but rather a Fresco issue.

I have created an issue at Fresco on August 22, 2019 and after some conversations and talkings, the only way for now to disable image downsample, is to compile Fresco from source after removing/comment out the downsample code inside DecodeProducer.java.

I have created a repository that has RN 0.61 and has detailed instructions on how to compile Fresco and disable image downsample. The repository can be found here: https://github.com/clytras/RN061FrescoBuild.

It turns out Fresco has a bug and does not apply Fresco configuration using ImagePipelineConfig and MainPackageConfig inside MainApplication.java, you can see more details about this here. RN has downsampling disabled by default! Until Fresco fixes this issue, the only way to disable image downsampling is to compile Fresco from source after removing the downsample code.

UPDATE FEB/2020

I have created a react-native-community/cli template that has RN 0.61.5 project and the required modifications to build Fresco from source. This is an easy and quick way to have a new RN project crafted with custom project name and with the changes needed to compile Fresco from source. It also uses Android NDK Revision 21 and I have tested it on macOS and Windows using yarn 1.21.

Github repository: clytras/react-native-fresco
NPM template: @lytrax/react-native-fresco

It can be installed like this:

npx @react-native-community/cli@next init --template=@lytrax/react-native-fresco <ProjectName>

There are detailed installation instruction in the README. You need to clone/patch Fresco using yarn fresco-setup and then install Android NDK and create android/libraries/fresco/local.properties with Android NDK path.

Swiping between tabs using createMaterialBottomTabNavigator for android

$
0
0

I have used React Navigation's createMaterialBottomTabNavigator to create a bottom tab navigator in my app. I want the screens to "slide" in from the left or right when the tab is changed, and swiping on the screen to be able to change tabs. I've looked into the documentation https://reactnavigation.org/docs/en/material-bottom-tab-navigator.html, and I can't find any configuration options that would make this happen. Why is this?

Viewing all 28468 articles
Browse latest View live