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

Render date of message above message in react-native-gifted-chat

$
0
0

Issue Description

Hello! When I render the message in a custom way, I can't show the creation date above the messages. How do I display this date? I tried to use the renderDay method, but it didn't work. Can anyone help? Pls

Steps to Reproduce / Code Snippets

I use renderMessage method to render the custom message:

...renderMessage(props) {    return (<Bubble        {...props}        wrapperStyle={{          left: {            backgroundColor: 'white',          },          right: {            backgroundColor: '#E8FAFF',          }        }}      />    );  }...render() {    return (<GiftedChat renderMessage={this.renderMessage.bind(this)}/>     );  }...

Additional Information

  • Nodejs version: 10.19.0
  • React version: 16.9.0
  • React Native version: 0.61.5
  • react-native-gifted-chat version: 0.13.0
  • Platform(s) (iOS, Android, or both?): Android

React-Native and Expo-av library, Audio: How to execute something right after a media audio finishes?

$
0
0

New Dev working on a React-Native app using the expo-av library to have background music playing.Right now, the Music Context folder looks like:

export const MusicProvider = props => {  const [gameSoundsPlay, setGameSoundsPlay] = useState(    initialState.mainThemePlay  )  const [soundObject, setSoundObject] = useState(initialState.mainThemePlay)  const startMusic = async () => {    mainTheme = new Audio.Sound()    try {      await mainTheme.loadAsync(require("../assets/sounds/ShortSong.mp3"))      await mainTheme.setStatusAsync({ isLooping: true })      await mainTheme.playAsync()      setSoundObject(mainTheme)    } catch (error) {      console.log("Couldnt load main theme")      return    }  }

With this, it plays a background song which loops over and over.I've been tasked with adding two more songs, and making it so that after the first song is finished, the 2nd song should play.

I'm using console.log to see if I can properly execute code once the first song finishes:

try {      await mainTheme.loadAsync(require("../assets/sounds/ShortSong.mp3"))      // Deleted the isLooping line so the song plays only once      await mainTheme.playAsync()      setSoundObject(mainTheme)      if (mainTheme.didJustFinish) {        console.log("First song has just finished.")      }

The docs say that, among the attributes available (like isLooping), is didJustFinish which is supposed to return a Boolean value once a Media finishes.

If I can get this simple console.log() to play on time, I can figure out how/when to add some functionality to get the second song playing.

Show one component in multiple or all screens

$
0
0

what's up?I'he been trying to add a custom reload button in all my screens, because in the future i'll change this element, but, I'm not getting it to work.

I already try to create a custo screen and put both, Navigator and Button, but it's not working, someone could give any tip?

Thanks for your help.

Component with both Navigator and Button:

const WrappedComponents = () => {    return (<><Navigator><ReloadButtonStyled /></Navigator></>    )}

This is my button:

import React from 'react'import { DevSettings } from 'react-native';import styled from 'styled-components'import IconFA from 'react-native-vector-icons/FontAwesome';const ReloadButtonStyled = () => {    const Container = styled.View`        background-color: #0779e4;        justify-content: center;        align-items: center;        width: 80px;        height: 80px;        border-radius: 40px;        position: absolute;        z-index:100;        bottom: 20px;        right: 20px;        elevation: 5;        `;    const TouchableWithoutFeedback = styled.TouchableWithoutFeedback``;    return (<TouchableWithoutFeedback onPress={() => DevSettings.reload()}><Container><IconFA name={'refresh'} size={40} color={'#f9f9f9'} /></Container></TouchableWithoutFeedback>    )};export default ReloadButtonStyled;

I want to put the Button in every screen, using navigationV5:

import 'react-native-gesture-handler';import React from 'react';import { NavigationContainer } from '@react-navigation/native';import { createStackNavigator } from '@react-navigation/stack';//import das telas usadas na navegaçãoimport MainScreen from '../screens/MainScreen';import DragDropScreen from '../screens/DragDropScreen';import WorkingExample from '../backups/WorkingExample'//criação da stack principalconst Stack = createStackNavigator();export default function MyStack() {    return (<NavigationContainer><Stack.Navigator                screenOptions={{                    headerShown: false,                }}><Stack.Screen                    name='MainScreen'                    component={MainScreen}                    options={{                        title: 'MainScreen'                    }}                /><Stack.Screen                    name='DragDropScreen'                    component={DragDropScreen}                    options={{                        title: 'DragDropScreen'                    }}                /><Stack.Screen                    name='WorkingExample'                    component={WorkingExample}                    options={{                        title: 'WorkingExample'                    }}                /></Stack.Navigator></NavigationContainer>    )}

React-Native Memory leak, possibly from redux, please see details

$
0
0

So I'm building a react-native application for my work, and I'm using redux and websockets. I'm experienced a bad memory leak when i go to the messenger screen repeatedly, which i suspect has something to do with redux actions / state changes being stored in memory. I have a pretty nested store object that is being modified when chat messages load/ a new message comes in. The leak is especially bad in debug mode, but improves significantly in production but the memory still climbs over time. Could someone take a look at my reducer and tell me if the way im modified nested properties in an array may be causing this and if there is any alternative? I'm also using "store.getState()" and store.dispatch() in the socket because it is not a react component so i have no other means of getting things like the auth token since there are no props.

I'm using a lot of .find() and .map() methods to modify my nested redux state (adding messages to a chat room) and im wondering if these objects are being stored in memory every time i trigger these functions. Any help would be much appreciated!Thank you

Here is my reducer:

const chatReducer = (state = {rooms: [], selectedChat: ''}, action) => {  switch (action.type) {    case 'LOAD_CHATS':      return {...state, rooms: [...state.rooms, ...action.rooms]};    case 'LOAD_MESSAGES':      const newRooms = state.rooms.map(room => {        if (room.id === state.selectedChat) {          room.messages = action.messages;        }        return room;      });      return {...state, rooms: newRooms};    case 'NEW_MESSAGE':      const newMessages = state.rooms.map(room => {        if (room.id === action.item.room) {          return {            ...room,            messages: [              ...room.messages,              {                user: action.item.user,                date: action.item.date,                message: action.item.msg,              },            ],          };        }        return room;      });      return {...state, rooms: newMessages};    case 'SELECTED_CHAT':      return {...state, selectedChat: action.id};    case 'SYNC_MESSAGES':      const roomById = state.rooms.find(room => room.id === action.id);      const syncedMessages = action.msgs.map(msg => {        if (!roomById.messages.find(el => el.id === msg.id)) {          return msg.messages;        }      });      const roomMessages = state.rooms.map(room => {        if (room.id === action.id) {          return {            ...room,            messages: [...room.messages, ...syncedMessages],          };        }        return room;      });      return {...state, rooms: roomMessages};    default:      return state;  }};export default chatReducer;

and here is my socket utilities file:

import io from 'socket.io-client';import {store} from '../redux/store';let socket = null;const getSocket = () => {  return socket;};const init = () => {  const token = store.getState().auth.token;  socket = io.connect('********************',    {      query: {token},      transports: ['websocket'],    },  );};const handleConnect = data => {  socket.on('connecting', () => {    console.log('Socket connecting...');  });  socket.on('connect', x => {    console.log('CONNECTED', x);    socket.emit('RegisterUser', {      User: data.username,      Client: data.client,      System: 'Mobile',    });  });  socket.on('ChatMessages', msgs => {    store.dispatch({type: 'LOAD_MESSAGES', messages: msgs[0].messages});  });  socket.on('UserTypeing', msg => {    store.dispatch({type: 'USER_TYPING', data: msg});  });  socket.on('UserTypeingStopped', msg => {    store.dispatch({type: 'STOPPED_TYPING', user: msg});  });  socket.on('NewMessage', msg => {    store.dispatch({type: 'NEW_MESSAGE', item: msg});  });  socket.on('SortedMessages', msgs => {    const id = store.getState().chat.selectedChat;    store.dispatch({type: 'SYNC_MESSAGES', msgs: msgs.resources, id});  });  socket.on('connect_failed', msg => {    console.log(msg, 'CONNECT FAILED');  });  socket.on('connect_error', msg => {    console.log(msg, 'Connect Error!');  });  socket.on('connect_timeout', msg => {    console.log(msg, 'timeout!');  });  socket.on('error', msg => {    console.log(msg, 'Error!');  });  socket.on('reconnect', attemptNumber => {    console.log('recon attempt:', attemptNumber);  });};const getRooms = () => {  socket.on('GetChatRooms', rooms => {    const arr = [];    rooms.forEach(room => {      if (!store.getState().chat.rooms.find(el => el.id === room.id)) {        arr.push(room);      }    });    if (arr.length) {      store.dispatch({type: 'LOAD_CHATS', rooms: arr});    }  });};const getRoomMessages = id => {  console.log('GETROOMMESSAGES');  socket.emit('GetChatMessages', id);};const userUpdate = () => {  socket.on('userupdate', data => {});};const handleDisconnect = () => {  socket.on('disconnect', () => {    console.log('DISCONNECTED');  });};const startTyping = roomId => {  socket.emit('SendRoomImTyping', {room: roomId});};const stopTyping = roomId => {  socket.emit('SendRoomStopTyping', {room: roomId});};const sendRoomMessage = (roomId, message) => {  socket.emit('SendRoomMessage', {room: roomId, message});};const updateRoomMessages = (id, start) => {  console.log(id, start);  socket.emit('GetChatMessagesFiltered', {id, start});};const disconnect = () => {  socket.disconnect();};const SocketTools = {  init,  handleConnect,  getRooms,  getRoomMessages,  updateRoomMessages,  userUpdate,  disconnect,  handleDisconnect,  getSocket,  sendRoomMessage,  startTyping,  stopTyping,};export default SocketTools;

React Native Android JNI crash

$
0
0

I start to get below error after React Native Activity loaded. We cleaned, removed, npm install, reimporting to android studio etc. Nothing solved.

My react-native info output is:

infoReact Native Environment Info:System:OS: macOS 10.14.5CPU: (8) x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHzMemory: 933.09 MB / 16.00 GBShell: 3.2.57 - /bin/bashBinaries:Node: 8.12.0 - /usr/local/bin/nodeYarn: 1.15.2 - /usr/local/bin/yarnnpm: 6.9.0 - /usr/local/bin/npmWatchman: 4.9.0 - /usr/local/bin/watchmanSDKs:iOS SDK:Platforms: iOS 12.2, macOS 10.14, tvOS 12.2, watchOS 5.2Android SDK:API Levels: 11, 14, 15, 16, 21, 22, 23, 24, 25, 26, 27, 28Build Tools: 21.1.2, 22.0.1, 23.0.1, 24.0.2, 25.0.0, 25.0.2, 26.0.0, 26.0.2, 27.0.0, 27.0.2, 27.0.3, 28.0.1, 28.0.3System Images: android-16 | Google APIs Intel x86 Atom, android-19 | Google APIs Intel x86 Atom, android-25 | Google APIs ARM EABI v7a, android-26 | Google Play Intel x86 Atom, android-28 | Google APIs Intel x86 AtomIDEs:Xcode: 10.2.1/10E1001 - /usr/bin/xcodebuildnpmPackages:react: 16.5.2 => 16.5.2react-native: 0.59.9 => 0.59.9npmGlobalPackages:react-native-cli: 2.0.1

I generate the JS bundle like below:

 rm -rf node_modules package-lock.json yarn.lock && npm install && npm run bundle-android -- --bundle-output ../src/main/assets/index.android.bundle --assets-dest ../src/main/res --reset-cache

After js bundle loaded the error logcat from android studio causing crash:

java_vm_ext.cc:542] JNI DETECTED ERROR IN APPLICATION: obj == nulljava_vm_ext.cc:542]     in call to GetObjectFieldjava_vm_ext.cc:542]     from void com.facebook.react.bridge.queue.NativeRunnable.run()java_vm_ext.cc:542] "mqt_js" prio=5 tid=73 Runnablejava_vm_ext.cc:542]   | group="main" sCount=0 dsCount=0 flags=0 obj=0x12e57180 self=0x737e710000java_vm_ext.cc:542]   | sysTid=4409 nice=-4 cgrp=default sched=0/0 handle=0x735b0de4f0java_vm_ext.cc:542]   | state=R schedstat=( 1245932303 9379164 417 ) utm=117 stm=7 core=4 HZ=100java_vm_ext.cc:542]   | stack=0x735afdb000-0x735afdd000 stackSize=1041KBjava_vm_ext.cc:542]   | held mutexes= "mutator lock"(shared held)java_vm_ext.cc:542]   native: #00 pc 00000000003c7d4c  /system/lib64/libart.so (art::DumpNativeStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, int, BacktraceMap*, char const*, art::ArtMethod*, void*, bool)+220)java_vm_ext.cc:542]   native: #01 pc 00000000004a5b64  /system/lib64/libart.so (art::Thread::DumpStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, bool, BacktraceMap*, bool) const+352)java_vm_ext.cc:542]   native: #02 pc 00000000002e98a8  /system/lib64/libart.so (art::JavaVMExt::JniAbort(char const*, char const*)+968)java_vm_ext.cc:542]   native: #03 pc 0000000000353b90  /system/lib64/libart.so (art::JNI::GetObjectField(_JNIEnv*, _jobject*, _jfieldID*)+1068)java_vm_ext.cc:542]   native: #04 pc 0000000000074aa8  /data/app/com.package.package-rAyjieGVX60Tt9IsiUFHKg==/lib/arm64/libreactnativejni.so (facebook::jni::HybridClass<facebook::react::WritableNativeMap, facebook::react::ReadableNativeMap>::JavaPart::cthis()+140)java_vm_ext.cc:542]   native: #05 pc 0000000000073d74  /data/app/com.package.package-rAyjieGVX60Tt9IsiUFHKg==/lib/arm64/libreactnativejni.so (facebook::react::MethodInvoker::invoke(std::__ndk1::weak_ptr<facebook::react::Instance>&, facebook::jni::alias_ref<facebook::jni::detail::JTypeFor<facebook::react::JBaseJavaModule, facebook::jni::JObject, void>::_javaobject*>, folly::dynamic const&)+4044)java_vm_ext.cc:542]   native: #06 pc 0000000000069b28  /data/app/com.package.package-rAyjieGVX60Tt9IsiUFHKg==/lib/arm64/libreactnativejni.so (facebook::react::JavaNativeModule::callSerializableNativeHook(unsigned int, folly::dynamic&&)+172)java_vm_ext.cc:542]   native: #07 pc 00000000000a2d88  /data/app/com.package.package-rAyjieGVX60Tt9IsiUFHKg==/lib/arm64/libreactnativejni.so (facebook::react::ModuleRegistry::callSerializableNativeHook(unsigned int, unsigned int, folly::dynamic&&)+84)java_vm_ext.cc:542]   native: #08 pc 000000000001d384  /data/app/com.package.package-rAyjieGVX60Tt9IsiUFHKg==/lib/arm64/libjscexecutor.so (facebook::react::JSIExecutor::nativeCallSyncHook(facebook::jsi::Value const*, unsigned long)+196)java_vm_ext.cc:542]   native: #09 pc 0000000000026cfc  /data/app/com.package.package-rAyjieGVX60Tt9IsiUFHKg==/lib/arm64/libjscexecutor.so (???)java_vm_ext.cc:542]   native: #10 pc 00000000000befa4  /data/app/com.package.package-rAyjieGVX60Tt9IsiUFHKg==/lib/arm64/libjsc.so (???)java_vm_ext.cc:542]   native: #11 pc 00000000004dc400  /data/app/com.package-rAyjieGVX60Tt9IsiUFHKg==/lib/arm64/libjsc.so (???)java_vm_ext.cc:542]   native: #12 pc 00000000004cce40  /data/app/com.package-rAyjieGVX60Tt9IsiUFHKg==/lib/arm64/libjsc.so (???)java_vm_ext.cc:542]   at com.facebook.react.bridge.queue.NativeRunnable.run(Native method)java_vm_ext.cc:542]   at android.os.Handler.handleCallback(Handler.java:891)java_vm_ext.cc:542]   at android.os.Handler.dispatchMessage(Handler.java:102)java_vm_ext.cc:542]   at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)java_vm_ext.cc:542]   at android.os.Looper.loop(Looper.java:207)java_vm_ext.cc:542]   at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:232)java_vm_ext.cc:542]   at java.lang.Thread.run(Thread.java:784)java_vm_ext.cc:542]A/libc: Fatal signal 6 (SIGABRT), code -6 (SI_TKILL) in tid 4409 (mqt_js), pid 3986 )

The device is Huawe p20 ProIt looks like some kind of JNI error firing from JNI side of the React native. Any ideas?Thanks

Google Play Console unsupported devices because of android.hardware.camera.autofocus

$
0
0

I just released an app on Google Play. It shows 1614 devices don't support my app because of this issue:

Doesn't support required feature - android.hardware.camera.autofocus

However, my Android Manifest shows this feature as required=false.

Here are the permissions and features I've declared:

<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WAKE_LOCK" /><permission    android:name="${applicationId}.permission.C2D_MESSAGE"    android:protectionLevel="signature" /><uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" /><uses-permission android:name="android.permission.VIBRATE" /><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/><uses-permission android:name="android.permission.CAMERA" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /><uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-feature android:name="android.hardware.camera.any" android:required="false" /><uses-feature android:name="android.hardware.microphone" android:required="false" /><uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />

Am I missing anything, or have I included anything that would cause the android.hardware.camera.autofocus feature to be required in my app?

For reference this is a React Native app.

React Native scroll view not showing

$
0
0

I have a scroll view at the top level of the view hierarchy. I'm trying to get it to show its content but I haven't had any luck.

I see that the documentation says scroll views need a bounded height to work. I can't seem to get it to have a bounded height. This is what I have so far.

'use strict';const React = require('react-native');const {  StyleSheet,  Text,  View,  BackAndroid,  TextInput,  TouchableNativeFeedback,  ScrollView} = React;const ActionButton = require('./action-button'),    Dimensions = require('Dimensions');module.exports = React.createClass({  handleBackButtonPress () {    if (this.props.navigator) {      this.props.navigator.pop();      return true;    }    return false;  },  componentWillMount () {    BackAndroid.addEventListener('hardwareBackPress', this.handleBackButtonPress);  },  componentWillUnmount () {    BackAndroid.removeEventListener('hardwareBackPress', this.handleBackButtonPress);  },  onInputFocus (refName) {    setTimeout(() => {      let scrollResponder = this.refs.getScrollResponder();      scrollResponder.scrollNativeHandleToKeyboard(        React.findNodeHandle(this.refs[refName]),        110,        true      );    }, 50);  },  render: function() {    return (<View style={styles.scrollWrapper}><ScrollView ref='scrollView' style={styles.scroller}><View style={styles.container}><View style={styles.header}><Text>New Post</Text><View style={styles.actions}><ActionButton handler={this.handleBackButtonPress} icon={'fontawesome|close'}                    size={15} width={15} height={15} /></View></View><View style={styles.content}><TextInput underlineColorAndroid={'white'}                placeholder={'Who\'s your professor?'}                ref='professor'                onFocus={this.onInputFocus.bind(this, 'professor')}                /><TextInput multiline={true}                underlineColorAndroid={'white'}                placeholder={'What do you think?'}                ref='post'                onFocus={this.onInputFocus.bind(this, 'post')}                /></View><View style={styles.footer}><TouchableNativeFeedback                background={TouchableNativeFeedback.SelectableBackground()}><View style={{width: 50, height: 25, backgroundColor: 'green'}}><Text>Submit</Text></View></TouchableNativeFeedback></View></View></ScrollView></View>    );  }});const styles = StyleSheet.create({  scrollWrapper: {    flex: 1  },  scroller: {    flex: 1  },  container: {    flex: 1,    flexDirection: 'column',    justifyContent: 'flex-start',    backgroundColor: 'white',    padding: 5,  },  post: {    flex: 1,  },  actions: {    flex: 1,    flexDirection: 'row',    justifyContent: 'flex-end',    alignSelf: 'center'  },  header: {    flex: 1,    position: 'absolute',    top: 0,    left: 0,    right: 0,    height: 35,    padding: 5,    flexDirection: 'row'  },  content: {    flex: 1,    position: 'absolute',    top: 35  },  footer: {    flex: 1,    position: 'absolute',    bottom: 0,    left: 0,    right: 0,    height: 35  }});

EDIT: So I changed the background colors of all the components to something obvious. I was able to simplify the view, so now the ScrollView is the root of the component. The container view (the immediate child of the ScrollView) is the one who isn't filling all the available space. I'm still playing around with it but any help is much appreciated.

Can't extract cities of country OpenWeather

$
0
0

I wanna use open-weather API for my application. for that i thought i might be able to save cities and their IDs in my own app in a json file and whenever i user wants a locations weather, app selects city's ID from json and make API call.

for that i downloaded a 30MB Json file provided by Openweather, it contains all countries and all theirs cities. putting a 30MB in my app isn't a good idea apparently. so i decided to extract my country cities only. but the point is, this idea could not be done. so many cities from different countries has same names. and extracted json was huge again. even some coutry codes are cities in other countries.

i wonder if there is a way better implementation. or any idea or way to extract just cities of a country.

any help to implement weather call in my app for different cities would be appreciated


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

$
0
0

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

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

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

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

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

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

There is no luck on solving this issue as well.

The codes following where the error returns

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

Here's my build.gradle

apply plugin: "com.android.application"apply plugin: 'io.fabric'import com.android.build.OutputFile/** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * */  project.ext.react = [    // the name of the generated asset file containing your JS bundle    bundleAssetName: "index.android.bundle",    // the entry file for bundle generation. If none specified and    // "index.android.js" exists, it will be used. Otherwise "index.js" is    // default. Can be overridden with ENTRY_FILE environment variable.    entryFile: "index.android.js",    // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format    bundleCommand: "ram-bundle",    // whether to bundle JS and assets in debug mode    bundleInDebug: false,    // whether to bundle JS and assets in release mode    bundleInRelease: true,    // whether to bundle JS and assets in another build variant (if configured).    // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants    // The configuration property can be in the following formats    //         'bundleIn${productFlavor}${buildType}'    //         'bundleIn${buildType}'    // bundleInFreeDebug: true,    // bundleInPaidRelease: true,    // bundleInBeta: true,    // whether to disable dev mode in custom build variants (by default only disabled in release)    // for example: to disable dev mode in the staging build type (if configured)    devDisabledInStaging: true,    // The configuration property can be in the following formats    //         'devDisabledIn${productFlavor}${buildType}'    //         'devDisabledIn${buildType}'    // the root of your project, i.e. where "package.json" lives    root: "../../",    // where to put the JS bundle asset in debug mode    jsBundleDirDebug: "$buildDir/intermediates/assets/debug",    // where to put the JS bundle asset in release mode    jsBundleDirRelease: "$buildDir/intermediates/assets/release",    // where to put drawable resources / React Native assets, e.g. the ones you use via    // require('./image.png')), in debug mode    resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",    // where to put drawable resources / React Native assets, e.g. the ones you use via    // require('./image.png')), in release mode    resourcesDirRelease: "$buildDir/intermediates/res/merged/release",    // by default the gradle tasks are skipped if none of the JS files or assets change; this means    // that we don't look at files in android/ or ios/ to determine whether the tasks are up to    // date; if you have any other folders that you want to ignore for performance reasons (gradle    // indexes the entire tree), add them here. Alternatively, if you have JS files in android/    // for example, you might want to remove it from here.    inputExcludes: ["android/**", "ios/**"],    // override which node gets called and with what additional arguments    nodeExecutableAndArgs: ["node"],    // supply additional arguments to the packager    extraPackagerArgs: []  ]project.ext.react = [    enableHermes: false,  // clean and rebuild if changing]apply from: "../../node_modules/react-native/react.gradle"/** * Set this to true to create two separate APKs instead of one: *   - An APK that only works on ARM devices *   - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */def enableSeparateBuildPerCPUArchitecture = false/** * Run Proguard to shrink the Java bytecode in release builds. */def enableProguardInReleaseBuilds = false/** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US.  Note that * this variant is about 6MiB larger per architecture than default. */def jscFlavor = 'org.webkit:android-jsc:+'/** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and mirrored here.  If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */def enableHermes = project.ext.react.get("enableHermes", false);android {    dexOptions {       javaMaxHeapSize "3g"    }    compileSdkVersion rootProject.ext.compileSdkVersion    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    defaultConfig {        applicationId "com.test.testtrace"        minSdkVersion rootProject.ext.minSdkVersion        targetSdkVersion rootProject.ext.targetSdkVersion        versionCode 1        versionName "1.0"        multiDexEnabled true        missingDimensionStrategy 'react-native-camera', 'general'    }    splits {        abi {            reset()            enable enableSeparateBuildPerCPUArchitecture            universalApk false  // If true, also generate a universal APK            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"        }    }    signingConfigs {        debug {            storeFile file('debug.keystore')            storePassword 'android'            keyAlias 'androiddebugkey'            keyPassword 'android'        }        release {            storeFile file('.keystore')            storePassword '-'            keyAlias '.keystore'            keyPassword '-'        }    }    buildTypes {        debug {            signingConfig signingConfigs.debug        }        release {            // Caution! In production, you need to generate your own keystore file.            // see https://facebook.github.io/react-native/docs/signed-apk-android.            signingConfig signingConfigs.release            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"        }    }    packagingOptions {        pickFirst "lib/armeabi-v7a/libc++_shared.so"        pickFirst "lib/arm64-v8a/libc++_shared.so"        pickFirst "lib/x86/libc++_shared.so"        pickFirst "lib/x86_64/libc++_shared.so"    }    // applicationVariants are e.g. debug, release    applicationVariants.all { variant ->        variant.outputs.each { output ->            // For each separate APK per architecture, set a unique version code as described here:            // https://developer.android.com/studio/build/configure-apk-splits.html            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]            def abi = output.getFilter(OutputFile.ABI)            if (abi != null) {  // null for the universal-debug, universal-release variants                output.versionCodeOverride =                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode            }        }    }}crashlytics {  enableNdk true}dependencies {    implementation fileTree(dir: "libs", include: ["*.jar"])    //noinspection GradleDynamicVersion    implementation "com.facebook.react:react-native:+"  // From node_modules    implementation project(path: ":@react-native-firebase_crashlytics")    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"    implementation project(':lottie-react-native')    implementation project(':react-native-splash-screen')    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {      exclude group:'com.facebook.fbjni'    }    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {        exclude group:'com.facebook.flipper'    }    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {        exclude group:'com.facebook.flipper'    }    if (enableHermes) {        def hermesPath = "../../node_modules/hermes-engine/android/";        debugImplementation files(hermesPath +"hermes-debug.aar")        releaseImplementation files(hermesPath +"hermes-release.aar")    } else {        implementation jscFlavor    }}// Run this once to be able to run the application with BUCK// puts all compile dependencies into folder libs for BUCK to usetask copyDownloadableDepsToLibs(type: Copy) {    from configurations.compile    into 'libs'}apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)apply plugin: 'com.google.gms.google-services'

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

Thank you

React Native offline App using react-native-sqlite-storage

$
0
0

I am new to react native. I want to build an offline react native app for storing user data (Basic user details, user personal documents, images, etc). I already gone through some documents about react-native-sqlite-storage and I would like to integrate it. But not sure,

  1. If I can recover all the user data when user delete application data
  2. What is advantage of using react-native-sqlite-storage than redux-persist for offline app development?

React Native : BLE, Discover & Broadcast (advertise data)

$
0
0

I'm very new to BLE APIs and capabilities. I want to achieve a "simple" thing. Let's say I'm developing the APP-X. I want to be able to scan other phone around me, with APP-X installed (exactly like this app here https://www.tracetogether.gov.sg/ ). I want to scan and filter the wanted devices via a "simple" metadata (advertising data ? specific for my app) within the signal emitted by the concerned phones. I'm stuck because Idk how to "emit" (broadcast) that custom signal.

Can you please help me find a way to do this in RN ?

I have already check those libs:

Many thanks

react-native-webview:clean :Unable to delete directory

$
0
0

react-native

cd android.\gradlew clean

error message:

Execution failed for task ':react-native-webview:clean'.> Unable to delete directory 'C:****\node_modules\react-native-webview\android\build'    Failed to delete some children. This might happen because a process has files open or has its working directory set in the target directory.    - C:****\node_modules\react-native-webview\android\build\intermediates\library_java_res\debug\res.jar

How can i copy bundle file to document directory in react native

$
0
0

I have json file in my bundle. I want to copy file to document directory.

   var path = RNFS.DocumentDirectoryPath +'/data.json'; RNFS.copyFile(`${RNFS.MainBundlePath}/assests/resource/data.json`, path)    .then(() => {        console.log('FILE COPIED');    })    .catch((err) => {        console.log(err.message);    });The file “data.json” couldn’t be opened because there is no such file.

'installDebug' not found in root project 'android' React Native

$
0
0

I am trying to run my project on the android simulator. When I run react-native run-android I am getting the following:

FAILURE: Build failed with an exception.* What went wrong: Task 'installDebug' not found in root project 'android'.* Try: Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.BUILD FAILED

If I run ./gradlew tasks I get:

Build Setup tasks-----------------init - Initializes a new Gradle build. [incubating]wrapper - Generates Gradle wrapper files. [incubating]Help tasks----------buildEnvironment - Displays all buildscript dependencies declared in root project 'android'.components - Displays the components produced by root project 'android'. [incubating]dependencies - Displays all dependencies declared in root project 'android'.dependencyInsight - Displays the insight into a specific dependency in root project 'android'.help - Displays a help message.model - Displays the configuration model of root project 'android'. [incubating]projects - Displays the sub-projects of root project 'android'.properties - Displays the properties of root project 'android'.tasks - Displays the tasks runnable from root project 'android'.

Any idea why I don't have a installDebug task in my project? How do I get it back?

How to disable screen capture/screenshot in react native app

$
0
0

I have came across few solutions specific for Android to prevent screen-capturing and taking screenshots. But how do i disable screen-capturing in react native in specific page/module?Thanks in advance!!


Not getting manga reader API for react-native app [closed]

$
0
0

I am creating a manga reader app in react-native and thus requires an API for fetching mangas. I have found Rapid API but they are not working as expected.

How to add custom font in react native android

$
0
0

I am learning react-native, trying to create some demo apps just for learning. I want to set fontFamily to roboto thin of my toolbar title.

I have added roboto thin ttf in assets/fonts folder of my android project, however it seems that it is creating issues while running app. I am getting this issue while running

react-native start

ERROR  EPERM: operation not permitted, lstat 'E:\Myntra\android\app\build\generated\source\r\debug\android\support\v7\appcompat'{"errno":-4048,"code":"EPERM","syscall":"lstat","path":"E:\\Myntra\\android\\app\\build\\generated\\source\\r\\debug\\android\\support\\v7\\appcompat"}Error: EPERM: operation not permitted, lstat 'E:\Myntra\android\app\build\generated\source\r\debug\android\support\v7\appcompat'    at Error (native)

When I am removing the font then it is working fine.I am unable to fix this issue, can anyone help me what can be the reason for this.

Thanks in advance.

How to add strike through on Text in react native?

$
0
0

Hey I want to add Strike Through in $10 amount for showing cut amount. Please check below :

<View style={styles.row}><View style={styles.inputWrapstotal}><Text style={styles.labelcolor}>16.7% Off</Text></View><View style={styles.inputWrapstotal}><Text style={styles.labelamount}>Rs $10</Text><Text style={styles.labelamountchange}> 12 </Text></View></View>

Please add css so that i can align in a line of both text , Thanks in Advance.

Please check the images enter image description here

How to hide the header from Tab navigation (bottom-tabs) in react navigation 5.x?

$
0
0

i am trying to use createBottomTabNavigator function for create bottom navigation tab, i want to hide the header, bellow the screenshot: my tab screenShot

this is my TabsNavigation.js

import React, { Component } from 'react';import Explore from '../Explore';import Settings from '../Settings';import Profile from '../Profile';import Search from '../Search';import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';import Icon from 'react-native-vector-icons/FontAwesome5';import colors from '../../../styles/colors/index';const Tab = createBottomTabNavigator();function MyTabs() {  return (<Tab.Navigator    screenOptions={({ route }) => ({      tabBarIcon: ({ focused, color, size }) => {        let iconName;        if (route.name === 'Explore') {          iconName = focused ? 'home': 'home';          color = focused ? colors.mainColor : colors.gray03;        } else if (route.name === 'Settings') {          iconName = focused ? 'cog' : 'cog';          color = focused ? colors.mainColor : colors.gray03;        }        else if (route.name === 'Search') {          iconName = focused ? 'search' : 'search';          color = focused ? colors.mainColor : colors.gray03;        }        else if (route.name === 'Profile') {          iconName = focused ? 'user-alt' : 'user-alt';          color = focused ? colors.mainColor : colors.gray03;        }        return <Icon name={iconName} size={30} color={color} />;      }        })}    tabBarOptions={{      activeTintColor: colors.mainColor,      inactiveTintColor: colors.gray03    }}><Tab.Screen name="Explore" component={Explore} /><Tab.Screen name="Search" component={Search} /><Tab.Screen name="Profile" component={Profile} /><Tab.Screen name="Settings" component={Settings} /></Tab.Navigator>  );}export default function TabsBottom() {  return (<MyTabs />    );}

How can I solve this?thanks

unexpecteted token M in JSON at position 0, react-native && expo && android

$
0
0

I'm using fetch at react-native app powered by expo,


  const onStartPress = (level) => {   setIsError(false);   setIsLoading(true);   fetch(    `https://cors-anywhere.herokuapp.com/http://www.cs.utep.edu/cheon/ws/sudoku/new/?size=9?level=${level}`,    {      headers: {'Content-Type': 'application/json',        Accept: 'application/json',    },  })  .then((response) => {   console.log(response);   return response.json()})  .then((json) => {    if (!json.squares) setIsError(true);    else {      let arr = Array.from({ length: 9 }, () => Array(9).fill(0));      json.squares.forEach((square) => {        let { x, y, value } = square;        arr[x][y] = value;      });      setInitPuzzle(arr);    }  })  .catch((e) => {    console.log(e);    setIsError(true);  });};

while this code working as expected on web env, at an android device/emulator it gives me (from catch log)


SyntaxError: Unexpected token M in JSON at position 0

The answeres I found on the web was either about 'Content-Type' and Accept (which didn't work for me, as added to my code), or manipulate the android manifest, which is tricky cause I don't want to eject expo.

console.log(response) on the web looks like


 body: ReadableStream bodyUsed: true headers: Headers {} ok: true redirected: false status: 200 statusText: "OK" type: "cors" url: "https://cors-an..."

on android -


  bodyUsed: true  headers: Headers {map: {…}}  //not an empty object as web ??  ok: false  status: 400  statusText: undefined  type: "default"  url: "https://cors..."  _bodyBlob: Blob {_data: {…}} //wasn't on web at all  _bodyInit: Blob {_data: {…}  //wasn't on web at all

Beside 400 response (which not make any sense to me, URL is a valid address!), there is no body at the android response, just those bodyBlob and bodyInitany solution? thanks in advance :)

Viewing all 28460 articles
Browse latest View live


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