I need some tips about this error. I think the code might need a bunch of 'try' and 'catch' functions? I am new to this and I don't know how to properly implement them.
Question: should the audio recorder record audio even with this warning happening?( this code is meant to integrate an audio recorder: Audio recorder npm package link )
Btw I am running the latest version of react native, I also only wrote code inside App.js (besides giving android permisions and completing the post-installation process) since in the latest version of react the linking of packages becomes Auto-Link which means the linking happens on installing a package (Source: https://reactnative.dev/blog/2022/06/21/version-069 )
App.js :
import React, {Component} from 'react';
import AudioRecorderPlayer from 'react-native-audio-recorder-player';
import {
StyleSheet,
View,
TouchableOpacity,
} from 'react-native';
const App = () => {
const audioRecorderPlayer = new AudioRecorderPlayer();
const onStartRecord = async () => {
const result = await this.audioRecorderPlayer.startRecorder();
this.audioRecorderPlayer.addRecordBackListener((e) => {
this.setState({
recordSecs: e.currentPosition,
recordTime: this.audioRecorderPlayer.mmssss(
Math.floor(e.currentPosition),
),
});
return;
});
console.log(result);
};
const onStopRecord = async () => {
const result = await this.audioRecorderPlayer.stopRecorder();
this.audioRecorderPlayer.removeRecordBackListener();
this.setState({
recordSecs: 0,
});
console.log(result);
};
const onStartPlay = async () => {
console.log('onStartPlay');
const msg = await this.audioRecorderPlayer.startPlayer();
console.log(msg);
this.audioRecorderPlayer.addPlayBackListener((e) => {
this.setState({
currentPositionSec: e.currentPosition,
currentDurationSec: e.duration,
playTime: this.audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
duration: this.audioRecorderPlayer.mmssss(Math.floor(e.duration)),
});
return;
});
};
const onPausePlay = async () => {
await this.audioRecorderPlayer.pausePlayer();
};
const onStopPlay = async () => {
console.log('onStopPlay');
this.audioRecorderPlayer.stopPlayer();
this.audioRecorderPlayer.removePlayBackListener();
};
return (
<View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onStartRecord}>
<Text style={styles.twhite}>Start Record</Text>
</TouchableOpacity>
</View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onStopRecord}>
<Text style={styles.twhite}>Stop Record</Text>
</TouchableOpacity>
</View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onStartPlay}>
<Text style={styles.twhite}>Start Play</Text>
</TouchableOpacity>
</View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onPausePlay}>
<Text style={styles.twhite}>Pause Play</Text>
</TouchableOpacity>
</View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onStopPlay}>
<Text style={styles.twhite}>Stop Play</Text>
</TouchableOpacity>
</View>
</View>
);
};
const styles = StyleSheet.create({
twhite: {
color:'white',
fontSize:18,
},
});
export default App;
Related
I'm trying to use Async Storage for a note app, I created a component called task.js as a template for todos, an navigation.js component for nav, and home.js for the main screen all display with <navigation /> inapp.js, I added a funcction to store object value using async storage, but is not working, everytime I hard reload the app everything will be gone but it is not giving me any errors, I don't know where to start
here is my Home.js
import React, {useState} from 'react';
import { Keyboard, KeyboardAvoidingView, Platform, StyleSheet, Text,
TextInput, TouchableOpacity, View, SafeAreaView, ScrollView, Image } from 'react-native';
import Task from '../components/Task';
import AsyncStorage from '#react-native-async-storage/async-storage';
export default function Home({ navigation }) {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
React.useEffect ( () => {
save(taskItems);
}, [taskItems])
React.useEffect (() => {
getsave();
}, [])
const handleAddTask = () => {
Keyboard.dismiss();
setTaskItems([...taskItems, task])
setTask(null);
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice (index, 1);
setTaskItems(itemsCopy)
}
const save = async taskItems =>{
try {
const savetask = JSON.stringify(taskItems)
await AsyncStorage.setItem('tasksave', savetask)
} catch (e) {
console.log(e);
}
};
const getsave = async () => {
try {
const taskItems = await AsyncStorage.getItem('tasksave');
if (taskItems != null){
setTaskItems(JSON.parse(taskItems));
}
} catch (error) {
console.log(e);
}
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Your stuff:</Text>
<TouchableOpacity onPress={() => navigation.navigate('About')}>
<Text style={styles.about}>About</Text>
</TouchableOpacity>
<ScrollView style={styles.items}>{
taskItems.map((item, index) => {
return (
<View key={index}>
<TouchableOpacity onPress={ () => navigation.navigate("Gas", {item})}>
<Task text={item} navigation={navigation} />
</TouchableOpacity>
<TouchableOpacity onPress={() => completeTask(index)} style={styles.deleteW}>
<Image style={styles.delete} source={require('../components/remove.png')}></Image>
</TouchableOpacity>
</View>
)
})
}
</ScrollView>
</View>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.textwrapper}>
<TextInput style={styles.input} placeholder={'message'} value={task} onChangeText={text => setTask(text)}></TextInput>
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrap}>
<Text style={styles.add}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
Here's my Task.js:
import React from "react";
import { View, Text, StyleSheet, Image, TouchableOpacity } from "react-native";
const Task = (props, {navigation}) => {
return (
<View style={styles.item}>
<View style={styles.itemleft}>
<Image style={styles.lightball} source={require('./arabic.png')}></Image>
<Text style={styles.itemtext}>{props.text}</Text>
</View>
<Image style={styles.arrow} source={require('./rightarrow.png')}></Image>
</View>
)
}
const styles = StyleSheet.create({
export default Task;
I hope is a quick read, I took out all the style stuff but this is still kinda long sorry, if you think it has something to do with my app.js or nav.js I can give you those too, I usually slove these bugs on my own but I just have no idea where to begin cause I'm not getting any error messages, thank you
I have 29 pronunciations stored in firebase storage and then from there with the help of access token, they're stored in realtime database. In UI, I've touchable opacity (in react native) to play those pronunciations one after the other in order. All pronunciations are getting played really fine and correctly till the 20th pronunciation but as long as i come at the 21st pronunciation, nothing is getting played from there onwards i have no idea why (by the way I have next and back buttons to show my data in order from database). But my other data (Text and images) is displayed correctly and normally, there's only a problem with audios. Can someone help me how to solve this problem? Also I have the same problem whether I use ref().on or ref().once. Here's the code given below:
import React from "react";
import Sound from "react-native-sound";
import database from '#react-native-firebase/database';
import {View, StyleSheet, Text, Image, ToastAndroid, Modal, TouchableOpacity} from 'react-native';
import { useState } from "react";
import { useEffect } from "react";
export default alphl=({navigation})=> {
const [myData,setData] = useState({
letter:'',
word:'',
wmeaning:'',
wimage:'',
apronun:'',
wpronun:'',
});
const [show, setshow]=useState(false);
const [wait, setwait]=useState();
const [img,setimg] = useState(null);
const [apronunn,setapronun] = useState(null);
const [wpronunn,setwpronun] = useState(null);
const [hey,sethey] = useState(1);
function inchey(){
sethey(hey + 1);
}
function decchey(){
sethey(hey - 1);
}
useEffect(() => {
ToastAndroid.showWithGravity('Wait! Loading...', ToastAndroid.LONG, ToastAndroid.CENTER);
getDatabase();
}, [hey]);
function getDatabase() {
database().ref('alphabets/'+hey+'/').once('value' , (snapshot) => {
console.log(snapshot.val());
// Sound.setCategory('Playback', true);
setwait(true);
var poo=new Sound(snapshot.val().apronun);
var pooo=new Sound(snapshot.val().wpronun);
setData({
letter: snapshot.val().letter,
word: snapshot.val().word,
wmeaning: snapshot.val().wmeaning,
wimage: setimg(snapshot.val().wimage),
apronun: setapronun(poo),
wpronun: setwpronun(pooo)
});
setwait(false);
});
// database().ref().off();
}
return (
<Text style={styles.lettertext}>
{myData ? myData.letter : 'loading...' }
</Text>
<TouchableOpacity onPress={() => {
return apronunn.play();
}}
disabled={wait}
style={styles.button}
>
<Text style={styles.buttontext}>Letter Pronunciation</Text>
</TouchableOpacity>
<Text style={styles.toptext}>
Word: {myData ? myData.word : 'loading...' }
</Text>
<Text style={styles.toptext}>
Meaning: {myData ? myData.wmeaning : 'loading...' }
</Text>
<TouchableOpacity onPress={() => {
return wpronunn.play();
}}
disabled={wait}
style={styles.button}
>
<Text style={styles.buttontext}>Word Pronunciation</Text>
</TouchableOpacity>
<Image style={{width:200, height:200, borderRadius:10, marginBottom:15}}
source={{uri: img}}
/>
<View>
<TouchableOpacity onPress={ () => {
if (hey>28) {
ToastAndroid.showWithGravity('Error! This is the last alphabet', ToastAndroid.CENTER, ToastAndroid.CENTER);
}
else {
inchey();
}
}}
style={styles.buttonnb}
>
<Text style={styles.buttontext}>Next</Text>
</TouchableOpacity>
<TouchableOpacity onPress={ async () => {
if (hey<2) {
ToastAndroid.showWithGravity('Error! Can not go back further', ToastAndroid.CENTER, ToastAndroid.CENTER);
}
else {
decchey();
}
}}
style={styles.buttonnb}
>
<Text style={styles.buttontext}>Back</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('alpht')}
style={styles.button}
>
<Text style={styles.buttontext}>Give Test</Text>
</TouchableOpacity>
</View>
</View>
);
}
I have a problem with React-Native. I want to show data from Django to React-Native, but I can't show one data, this is the code:
import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, Image, FlatList } from "react-native";
import client from "./../../api/client";
const DetailView = ({navigation, route}) => {
const [detail, setDetail] = useState("");
const { objurl } = route.params;
const getDetail = async (url) => {
try {
const response = await client.get(url);
if (!response.ok) {
setDetail(response.data);
}
} catch (error) {
console.log(error);
}
};
useEffect(()=>{ getDetail(objurl); }, [])
console.log(detail.habilidad_usuario.nombre_habilidad);
return (
<View style={styles.center}>
<Image
style={styles.usuarioImage}
source={{
uri: detail.foto_usuario,
}}
/>
<Text style={styles.name}>{detail.nombre_usuario} {detail.apellido_usuario}</Text>
<Text style={styles.name}>{detail.habilidad_usuario.nombre_habilidad}</Text>
<Text style={styles.description}>{detail.descripcion_usuario} </Text>
<Text style={styles.body}>Dirección: {detail.direccion_usuario} </Text>
<Text style={styles.body}>Celular: {detail.id_usuario} </Text>
<FlatList
data={detail.usuario_comentado}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => {
return (
<Text style={styles.body}>Comentario: {item.contenido_comentario} </Text>
);
}}
/>
</View>
);
}
The problem is in the line:
<Text style={styles.name}>{detail.habilidad_usuario.nombre_habilidad}</Text>
and It's the result:
enter image description here
The others data is rendering very well.
The data from Django Rest is:
enter image description here
I think I am getting something wrong, I keep getting an error of 'this.deliveryFareEstimate() is undefined'
I am trying to sum up values gotten from a prop, but its not working as planned, and I think maybe doing it wrong tho. I am roughly new to programming generally.
Below is a sample code I am using to achieve it.
import React, { Component } from "react";
import { View, Text, StyleSheet, Image, TouchableOpacity, SafeAreaView, StatusBar } from "react-native";
import { Ionicons } from "#expo/vector-icons";
import RNSlidingButton, { SlideDirection } from "../../components/RNSlidingButton";
import { Block } from "../../components";
const PerKm = 55;
const PerKg = 35;
export default class ConfirmBooking extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { handleBackPress, estimatedWeight, deliveryDuration } = this.props;
FareEstimate = () => {
const totalDistanceCost = PerKm * deliveryDuration;
const totalParcelWeight = PerKg * estimatedWeight;
const estimatedFare = totalParcelWeight + totalDistanceCost;
return estimatedFare;
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
{/* Delivery Details */}
<View style={styles.header}>
<TouchableOpacity
onPress={handleBackPress}
style={styles.navBarButton}
>
<Ionicons name="md-arrow-back" size={23} color="#FFF" />
</TouchableOpacity>
<Text style={styles.headerText}> Details</Text>
</View>
{/* content holder */}
<View style={styles.content}>
<Block style={styles.generalBlock}>
<Text style={styles.generalBlockHeaderText}>
ETA from Pick up
</Text>
<Text style={styles.generalBlockText}>
{deliveryDuration} Mins
</Text>
</Block>
<Block style={styles.generalBlock}>
<Text style={styles.generalBlockHeaderText}>
Estimated Parcel Weight
</Text>
<Text style={styles.generalBlockText}>{estimatedWeight} Kg</Text>
</Block>
<View style={styles.fareAndConfirm}>
<Text style={styles.fareAndConfirmHeaderText}>Fare</Text>
<Text style={styles.fareAndConfirmText}>
${this.FareEstimate()}
</Text>
</View>
</View>
</View>
</SafeAreaView>
);
}
}
FareEstimate is not properly defined. Always use const or let to define a local variable.
const FareEstimate = () => {
const totalDistanceCost = PerKm * deliveryDuration;
const totalParcelWeight = PerKg * estimatedWeight;
const estimatedFare = totalParcelWeight + totalDistanceCost;
return estimatedFare;
};
Since FareEstimate is defined locally inside render(), Call it without this
<Text style={styles.fareAndConfirmText}>${FareEstimate()}</Text>
So I'm trying to attach a .on listener, like so
firebase.database().ref('Users').child('AhvRcIT2anTaucSDoOgt2MLNxgZ2').on('value', snap => {
const user = snap.val();
alert(true);
}).catch(e => alert(e))
The problem is, I get an error saying
Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground. See https://github.com/facebook/react-native/issues/12981 for more info. (Saw setTimeout with duration 398331ms)
which I guess makes sense. The only solutions I could find were to just hide the warning, which sounds like a bad idea. Especially that my app started freezing after a while when I added this listener.
I know there is react-native-firebase available, but I've read all it does, is just hide the warning, not really solving the problem.
How can this problem be solved though? Or does it just have to be like this on Android?
Entire home class
export default class HomeScreen extends React.Component {
static navigationOptions = {
header: null,
};
componentWillMount() {
(async () => {
await firebase.auth().signInAndRetrieveDataWithEmailAndPassword('loigin', 'pass');
const val = await firebase.database().ref('Users').child('AhvRcIT2anTaucSDoOgt2MLNxgZ2').once('value').then(r => r.val()).catch(e => alert(e));
alert(val);
})();
}
render() {
// firebase.database().ref('Users').child('AhvRcIT2anTaucSDoOgt2MLNxgZ2').on('value', snap => {
// const user = snap.val();
// alert(true);
// }).catch(e => alert(e))
alert(false)
return (
<View style={styles.container}>
<ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>
<View style={styles.welcomeContainer}>
<Image
source={
__DEV__
? require('../assets/images/robot-dev.png')
: require('../assets/images/robot-prod.png')
}
style={styles.welcomeImage}
/>
</View>
<View style={styles.getStartedContainer}>
{this._maybeRenderDevelopmentModeWarning()}
<Text style={styles.getStartedText}>Get started by opening</Text>
<View style={[styles.codeHighlightContainer, styles.homeScreenFilename]}>
<MonoText style={styles.codeHighlightText}>screens/HomeScreen.js</MonoText>
</View>
<Text style={styles.getStartedText}>
Change this text and your app will automatically reload.
</Text>
</View>
<View style={styles.helpContainer}>
<TouchableOpacity onPress={this._handleHelpPress} style={styles.helpLink}>
<Text style={styles.helpLinkText}>Help, it didn’t automatically reload!</Text>
</TouchableOpacity>
</View>
</ScrollView>
<View style={styles.tabBarInfoContainer}>
<Text style={styles.tabBarInfoText}>This is a tab bar. You can edit it in:</Text>
<View style={[styles.codeHighlightContainer, styles.navigationFilename]}>
<MonoText style={styles.codeHighlightText}>navigation/MainTabNavigator.js</MonoText>
</View>
</View>
</View>
);
}
_maybeRenderDevelopmentModeWarning() {
if (__DEV__) {
const learnMoreButton = (
<Text onPress={this._handleLearnMorePress} style={styles.helpLinkText}>
Learn more
</Text>
);
return (
<Text style={styles.developmentModeText}>
Development mode is enabled, your app will be slower but you can use useful development
tools. {learnMoreButton}
</Text>
);
} else {
return (
<Text style={styles.developmentModeText}>
You are not in development mode, your app will run at full speed.
</Text>
);
}
}
_handleLearnMorePress = () => {
WebBrowser.openBrowserAsync('https://docs.expo.io/versions/latest/guides/development-mode');
};
_handleHelpPress = () => {
WebBrowser.openBrowserAsync(
'https://docs.expo.io/versions/latest/guides/up-and-running.html#can-t-see-your-changes'
);
};
}
You can try below for your componentWillMount
componentWillMount() {
firebase
.auth()
.createUserWithEmailAndPassword('loigin', 'pass')
.then(() => {
firebase.database()
.ref('Users')
.child('AhvRcIT2anTaucSDoOgt2MLNxgZ2').on('value', function (snapshot) {
alert(snapshot.val())
})
.catch(e => alert(e));
})
.catch(error => {
alert(error.message)
})
}