I can't view the picture in the firebase storage - react-native

my get code
` getImage = async (imageUrl) => {
const user = firebase.auth().currentUser;
const url = await storage()
.ref(`Users/${user.uid}/picture`)
.getDownloadURL()
console.log(url)
imageUrl = url;
let imgSource = { uri: imageUrl }; // change this line
if (isNaN(imageUrl)) {
imgSource = { uri: this.state.imageUrl };
if (Platform.OS == 'android') {
imgSource.uri = "file:///" + imgSource.uri;
}
}
}
render() {
let {imageUrl} = this.state;
return (
<View>
<Image source={this.getImage(imageUrl)} style={{width:200,height:200}}/>
</View>
`
console screenshot
I can get the url from my console but the picture is not showing in my app, what's the problem

This might help
state = { newImageURL : undefined }
getImage = async (imageUrl) => {
const user = firebase.auth().currentUser;
const url = await storage()
.ref(`Users/${user.uid}/picture`)
.getDownloadURL()
console.log(url)
imageUrl = url;
let imgSource = { uri: imageUrl }; // change this line
if (isNaN(imageUrl)) {
imgSource = { uri: this.state.imageUrl };
if (Platform.OS == 'android') {
imgSource.uri = "file:///" + imgSource.uri;
}
}
this.setState({ newImageURL: imgSource }); // update code here
}
componentDidMount(){
let {imageUrl} = this.state;
this.getImage(imageUrl)
}
render() {
return (
<View>
{newImageURL ? <Image source={newImageURL} style={{width:200,height:200}}/> : null }
</View>

Related

How to remove previous audio when clicked on another audio play button? React-native expo

Im new to react native so please be gentle.
When i press back from the player component and select another audio, the new audio is played on top of the old audio.
Im adding this sentences otherwise stackoverflow doesnt let me post question because there is no much text.
This is service file for all the functions
export const play = async (playObject, uri) => {
try {
return await playObject.loadAsync(uri, { shouldPlay: true });
} catch (error) {
console.log(error.message);
}
};
// pause audio
export const pause = async (playObject) => {
try {
return await playObject.setStatusAsync({ shouldPlay: false });
} catch (error) {
console.log(error.message);
}
};
// resume audio
export const resume = async (playObject) => {
try {
return await playObject.setStatusAsync({ shouldPlay: true });
} catch (error) {
console.log(error.message);
}
};
// select another audio
export const playAnother = async (playObject, uri) => {
try {
await playObject.stopAsync();
await playObject.unloadAsync();
return await play(playObject, uri);
} catch (error) {
console.log(error.message);
}
};```
This is the player component
import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native';
import { pause, play, resume, getAudio, playAnother } from '../services/audioController';
import { getImage, getTitle } from '../services/dynamicName';
import { useEffect, useState } from 'react';
import { Audio } from 'expo-av';
import Slider from '#react-native-community/slider';
import PlayerButton from './PlayerButton';
export default function Prayer({ navigation, route }) {
const [playing, setPlaying] = useState(false);
const [sound, setSound] = useState(null);
const [playObject, setPlayObject] = useState(null);
// keeping track of current audio
const [currentAudio, setCurrentAudio] = useState(null);
const [playbackPosition, setPlaybackPosition] = useState(null);
const [playbackDuration, setPlaybackDuration] = useState(null);
const nextBtn = async () => {
setPlaybackPosition(playbackPosition + 10000);
};
const prevBtn = () => {
alert('ptre');
};
// get the duration and current position of the audio
const onPlaybackStatusUpdate = (playbackStatus) => {
if (playbackStatus.isLoaded && playbackStatus.isPlaying) {
setPlaybackPosition(playbackStatus.positionMillis);
setPlaybackDuration(playbackStatus.durationMillis);
}
};
const calculateSeekBar = () => {
if (playbackPosition !== null && playbackDuration !== null) {
return playbackPosition / playbackDuration;
}
return 0;
};
// play the audio
let cancel = false;
const playSound = async () => {
if (cancel) return;
try {
// playing audio for the first time
if (sound === null) {
const playObject = new Audio.Sound();
const status = await play(playObject, getAudio(route.params));
setPlayObject(playObject);
setSound(status);
setPlaying(true);
setCurrentAudio(route.params); //setting an id for current audio
return playObject.setOnPlaybackStatusUpdate(onPlaybackStatusUpdate);
}
// pause the audio
if (sound.isLoaded && sound.isPlaying) {
const status = await pause(playObject);
setSound(status);
setPlaying(false);
}
// resume the audio
if (sound.isLoaded && !sound.isPlaying && currentAudio === route.params) {
const status = await resume(playObject);
setSound(status);
setPlaying(true);
}
// another audio
if (sound.isLoaded && currentAudio !== route.params) {
const status = await playAnother(playObject, getAudio(route.params));
setSound(status);
setCurrentAudio(route.params);
}
} catch (e) {
console.log(e.message);
}
return () => {
cancel = true;
};
};
return (
<View style={styles.container}>
<View>
<Text style={styles.audioCount}>{route.params}/10</Text>
<Image style={styles.image} source={getImage(route.params)} />
<Text style={styles.title}>{getTitle(route.params)}</Text>
<View style={styles.controllerContainer}>
<Slider
style={{ width: '100%', height: 40, marginBottom: 20 }}
minimumValue={0}
maximumValue={1}
value={calculateSeekBar()}
minimumTrackTintColor="grey"
maximumTrackTintColor="#000000"
/>
<PlayerButton
playSound={playSound}
playing={playing}
prevBtn={prevBtn}
nextBtn={nextBtn}
/>
</View>
</View>
</View>
);
}
And also the slider and next and previous buttons functionality is not yet done. If anyone can help me, it would be so great. Thanks

Trying to make a real time object detection with TFjs and React Native, always gives the same prediction and stops when camera is opened

When the camera opens a blank camera appears for a few seconds and it always gives the same below output and stops.
prediction: [{"className":"nematode, nematode worm, roundworm","probability":0.050750732421875},{"className":"matchstick","probability":0.043731689453125},{"className":"lighter, light, igniter, ignitor","probability":0.021453857421875}]
Any idea how I can make the real time prediction work? without getting a false prediction as above just for one time
Below is the Camera Screen code where the prediction should happen in real time camera feed when user scans a certain surrounding
export function CameraScreen() {
const [word, setWord] = useState("");
const [predictionFound, setPredictionFound] = useState(false);
const [hasPermission, setHasPermission] = useState();
const [model, setModel] = useState();
const TensorCamera = cameraWithTensors(Camera);
let requestAnimationFrameId = 0;
const textureDims =
Platform.OS === "ios"
? { width: 1080, height: 1920 }
: { width: 1600, height: 1200 };
const tensorDims = { width: 152, height: 200 };
async function loadModel() {
try {
const model = await mobilenet.load();
setModel(model);
console.log("set loaded Model");
} catch (err) {
console.log(err);
console.log("failed load model");
}
}
useEffect(() => {
(async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === "granted");
await tf.ready();
await loadModel();
console.log("after model load");
})();
}, []);
const getPrediction = async (tensor) => {
if (!tensor) {
return;
}
const prediction = await model.classify(tensor);
console.log(`prediction: ${JSON.stringify(prediction)}`);
if (!prediction || prediction.length === 0) {
cancelAnimationFrame(requestAnimationFrameId);
console.log("no predictions found");
setPredictionFound(false);
return;
} else {
setPredictionFound(true);
}
};
const handleCameraStream = (imageAsTensors) => {
const loop = async () => {
const nextImageTensor = await imageAsTensors.next().value;
await getPrediction(nextImageTensor);
requestAnimationFrameId = requestAnimationFrame(loop);
};
if (!predictionFound) {
loop();
}
};
const renderCameraView = () => {
return (
<View style={styles.cameraView}>
<TensorCamera
style={styles.camera}
type={Camera.Constants.Type.back}
zoom={0}
cameraTextureHeight={textureDims.height}
cameraTextureWidth={textureDims.width}
resizeHeight={tensorDims.height}
resizeWidth={tensorDims.width}
resizeDepth={3}
onReady={handleCameraStream}
/>
</View>
);
};
useEffect(() => {
return () => {
cancelAnimationFrame(requestAnimationFrameId);
};
}, [requestAnimationFrameId]);
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>My Pictionary</Text>
</View>
{model ? (
<View style={styles.body}>{renderCameraView()}</View>
) : (
<Text>Still loading</Text>
)}
</View>
);
}
In the function handleCameraStream you stop looping the function once a prediction is found. In your case you would want to constantly run the loop as you want to make predictions on all the frames not a single one.
const handleCameraStream = (imageAsTensors) => {
const loop = async () => {
const nextImageTensor = await imageAsTensors.next().value;
await getPrediction(nextImageTensor);
requestAnimationFrameId = requestAnimationFrame(loop);
};
loop();
};

can not find the variable location with reversegeocodeAsync

Hello everyone who sees that question
I need help in that and full of hope that someone is gonna help
I am trying to get the exact location for the user to pass it finally in some other functionalities. I am using Expo init and expo-location
while using (reversegeocodeAsync({})) for the first render it's giving me the correct location but while testing it's crashing and giving an error and even works it's not making the data like after setting state it's not being available globally to use it
I tried different ways
First : use all the functions inside the same page but it doesn't work
import React, {useState, useEffect, useMemo} from 'react';
import {View, Text, StyleSheet, FlatList } from 'react-native';
import { NavigationEvents } from 'react-navigation';
import TimeApi from '../compnents/TimeApi';
import * as Location from 'expo-location';
const LocationScren = () => {
const [time, setsTime] = useState({});
const [errorMsg, setErrorMsg] = useState('');
const [location, setLocation ] = useState(null);
const [city, setCity ] = useState();
const getLocation = async () => {
let {status} = await Location.requestPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Access to Location denied');
}
const location = await Location.getCurrentPositionAsync({});
setLocation(location)
}
const getCity = async () => {
const place = await Location.reverseGeocodeAsync({
latitude : location.coords.latitude,
longitude : location.coords.longitude
});
place.find( p => {setCity(p.city);
})
}
const getTime = async () => {
const response = await TimeApi.get(`/${city}.json`);
setTime(response.data);
}
useEffect(() => {
getTime(), getLocation(), getCity();
} , []);
console.log(time);
console.log(location);
console.log(city);
return (
<View>
<FlatList
data = {time.items}
keyExtractor = {time => time.first}
renderItem = {({item}) => {
return (
<View>
<Text> {item.first} </Text>
<Text> {item.secnd} </Text>
<Text> {item.third} </Text>
<Text> {item.fourth} </Text>
<Text> {item.fifth} </Text>
<Text> {item.sixth} </Text>
</View>
);
}}
/>
{errorMsg ? <Text> {errorMsg} </Text> : null }
</View>
);
}
const styles = StyleSheet.create({});
export default LocationScren;
in here in the first render it's giving errors, then work , then giving that error ( null is not an object (evaluating 'location.coords')] )
Then I create a context file and added my functions and still getting the same error exactly
import createDataContext from './createDataContext';
import * as Location from 'expo-location';
const mwaqeetReducer = (state,action) => {
switch(action.type) {
case 'get_location' :
return action.payload;
case 'add_error' :
return {...state, errorMessage : action.error};
case 'get_city' :
return { cityName : action.payload};
default:
return state;
}
}
const getLocation = dispatch => async () => {
let {status} = await Location.requestPermissionsAsync();
if (status === !'granted') {
dispatch({type: 'add_error' , error : 'Permission to access location denied'});
}
let location = await Location.getCurrentPositionAsync({});
dispatch({type : 'get_location' , payload : location});
console.log(location);
}
const getCity = dispatch => async () => {
let keys = {
latitude : location.coords.latitude,
longitude : location.coords.longitude
}
const place = await Location.reverseGeocodeAsync(keys);
place.find( p => p.city);
dispatch({type : 'get_city' , payload : place});
console.log(place);
}
export const {Provider, Context} = createDataContext(
mwaqeetReducer, {
getLocation, getCity
} , {
errorMessage : '', location : {}, cityName : ''
}
)
so, please I need help to get over that.
You can try something like this.
useEffect(() => {
runFunction();
} , []);
const runFunction = async () => {
let {status} = await Location.requestPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Access to Location denied');
}
const location = await Location.getCurrentPositionAsync({});
setLocation(location)
const place = await Location.reverseGeocodeAsync({
latitude : location.coords.latitude,
longitude : location.coords.longitude
});
let city;
place.find( p => {
city = p.city
setCity(p.city)
});
const response = await TimeApi.get(`/${city}.json`);
setTime(response.data);
}

State is not updating even by callvack in render

i am trying to fetch data from some source and storing it in some variable .
But I come with an error that state is not updating.
this.setState({imgLink: data.items[0].snippet.thumbnails.default.url},
() =>
{
console.log(this.state.imgLink);
});
I wanted to print the new value in render method but it shows me nothing.
import React,{Component} from 'react';
import {View,Text,TextInput,ScrollView,Image} from
'react-native';
import { Icon } from 'react-native-elements';
import YTSearch from 'youtube-api-search';
import styles from './StatsStyle';
const API_KEY = '' // hided for stackoverflow ;
var query = '';
export default class StatsScreen extends Component
{
constructor(props)
{
super(props);
this.state = {
term: '',
imgLink: '',
width: 0,
height: 0,
title: '',
totalViews: 0,
totalSubs: 0,
totalVideos: 0 ,
channelId : '' ,
url: '',
}
};
fetchData = data => {
console.log('this is fetchData',data.items[0].statistics.subscriberCount);
this.setState({imgLink: data.items[0].snippet.thumbnails.default.url},
() =>
{
console.log('llllll',this.state.imgLink);
});
console.log('llllll',this.state.imgLink);
this.setState({width: data.items[0].snippet.thumbnails.default.url.width});
this.setState({height: data.items[0].snippet.thumbnails.default.url.height});
this.setState({title: data.items[0].snippet.title});
this.setState({totalSubs: data.items[0].statistics.subscriberCount});
this.setState({totalViews: data.items[0].statistics.viewCount});
this.setState({totalVideos: data.items[0].statistics.videoCount});
}
updateSubscribers = response =>
{
this.setState({totalSubs:
response.items[0].statistics.subscriberCount});
}
onPressedButton = channelId =>
{
var url =
'https://www.googleapis.com/youtube/v3/channels?
key='+API_KEY+'&id=' + channelId +
'&part=snippet,contentDetails,statistics';
this.setState({url: url});
return fetch(url)
.then((response) =>
{
return response.json();
console.log("popo",response);
})
// fetchData(data);
.then((data) => {
this.fetchData(data);
console.log('lol',this.state.imgLink);
console.log('hello',this.state);
})
.catch((error) => {
console.log(error);
})
//now fetching the response from the yt api again
//and again
.setInterval(() =>
{
var url =
'https://www.googleapis.com/youtube/v3/channels?
key='+API_KEY+'o&id=' + channelId +
'&part=statistics';
return fetch(url)
.then((response) =>
{
return response.json()
})
.then((data) => {
this.updateSubscribers(data)
},0)
.catch((error) => {
console.log(error);
});
});
}
render()
{
let{imgLink,totalSubs,totalViews,totalVideos,width,
height,title,channelId,videos,loading,term} =
this.state;
return(
<View style = {styles.container}>
<ScrollView>
<View style = {styles.results}>
<Image style = {
{
width:width,height:height,
alignItems:'center',borderRadius:50
,marginLeft:'auto',marginRight: 'auto',marginTop:
30
}
}
source = {{uri: imgLink}}/>
<Text style = {styles.title}>{title}</Text>
<Text style = {{fontSize: 40,fontWeight:
'bold'}}>Subscribers</Text>
<Text style = {styles.subs}>{totalSubs}</Text>
<Text style = {{fontSize: 40,fontWeight:
'bold'}}>TotalViews</Text>
<Text style = {styles.views}>{totalViews}</Text>
<Text style = {{fontSize: 40,fontWeight:
'bold'}}>TotalVideos</Text>
<Text style = {styles.videos}>{totalVideos}</Text>
</View>
</ScrollView>
</View>
);
}
}

React-Native pass Textinputvalue to other js

i'm a very newbie to react-native, so sry for this kind of question.
I have to implement a app with that i can log into our website. More details later.
First problem:
LoginScreen.js
var Animated = require('Animated');
var Dimensions = require('Dimensions');
var Image = require('Image');
var React = require('React');
var StatusBar = require('StatusBar');
var StyleSheet = require('StyleSheet');
var View = require('View');
var {
Text
} = require('OnTrackText');
var LoginButton = require('../common/LoginButton');
var TouchableOpacity = require('TouchableOpacity');
var TextInput = require('TextInput');
var {
skipLogin
} = require('../actions');
var {
connect
} = require('react-redux');
class LoginScreen extends React.Component {
state = {
anim: new Animated.Value(0),
name: '',
password: ''
};
componentDidMount() {
Animated.timing(this.state.anim, {
toValue: 3000,
duration: 3000
}).start();
}
render() {
return ( < Image style = {
styles.container
}
source = {
require('./img/login-background.png')
} >
< StatusBar barStyle = "default" / >
< TouchableOpacity accessibilityLabel = "Skip login"
accessibilityTraits = "button"
style = {
styles.skip
}
onPress = {
() => this.props.dispatch(skipLogin())
} >
< Animated.Image style = {
this.fadeIn(2800)
}
source = {
require('./img/x.png')
}
/>
</TouchableOpacity >
< View style = {
styles.section
} >
< Animated.Image style = {
this.fadeIn(0)
}
source = {
require('./img/ontrack-logo#3x.png')
}
/>
</View >
< View style = {
styles.section
} >
< Animated.Text style = {
[styles.h1, this.fadeIn(700, -20)]
} >
Willkommen zur < /Animated.Text>
<Animated.Text style={[styles.h1, {marginTop: -10}, this.fadeIn(700, 20)]}>
OnTrack App
</Animated.Text >
< /View>
<View style={styles.section}>
<TextInput
style={styles.input}
onChangeText={(text) => this.setState({ name: text }) }
value={this.state.name}
placeholder={"Benutzername"}
/ >
< TextInput style = {
styles.input
}
onChangeText = {
(text) => this.setState({
password: text
})
}
value = {
this.state.password
}
secureTextEntry = {
true
}
placeholder = {
"Password"
}
/>
</View >
< Animated.View style = {
[styles.section, styles.last, this.fadeIn(2500, 20)]
} >
< LoginButton name = {
this.state.name
}
password = {
this.state.password
}
source = "First screen" / >
< /Animated.View>
</Image >
);
}
fadeIn(delay, from = 0) {
....
}
const scale = Dimensions.get('window').width / 375;
var styles = StyleSheet.create({
....
}
});
module.exports = connect()(LoginScreen);
As you can see i would like to enter the name and password into the textinput.
Than
the LoginButton.js
'use strict';
const React = require('react');
const {StyleSheet} = require('react-native');
const { logInToWeb } = require('../actions');
const {connect} = require('react-redux');
class LoginButton extends React.Component {
props: {
style: any;
source?: string; // For Analytics
dispatch: (action: any) => Promise;
onLoggedIn: ?() => void;
};
state: {
isLoading: boolean;
};
_isMounted: boolean;
constructor() {
super();
this.state = { isLoading: false };
}
componentDidMount() {
this._isMounted = true;
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
if (this.state.isLoading) {
return (
<OnTrackButton
style={[styles.button, this.props.style]}
caption="Please wait..."
onPress={() => {}}
/>
);
}
return (
<OnTrackButton
style={[styles.button, this.props.style]}
// icon={require('../login/img/f-logo.png')}
caption="Login to OnTrack"
// onPress={this.props.onpress}
onPress={() => this.logIn()}
/>
);
}
async logIn() {
const {dispatch, onLoggedIn, name, password} = this.props;
this.setState({isLoading: true});
try {
await Promise.race([
dispatch(logInToWeb(name,password)),
timeout(15000),
]);
} catch (e) {
const message = e.message || e;
if (message !== 'Timed out' && message !== 'Canceled by user') {
alert(message);
console.warn(e);
}
return;
} finally {
this._isMounted && this.setState({isLoading: false});
}
onLoggedIn && onLoggedIn();
}
}
async function timeout(ms: number): Promise {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Timed out')), ms);
});
}
var styles = StyleSheet.create({
...
});
module.exports = connect()(LoginButton);
Than
the dispatch(logInToWeb)method in ./action/login.js looks like this:
'use strict';
import type { Action, ThunkAction } from './types';
const Parse = require('parse/react-native');
const {Platform} = require('react-native');
const Alert = require('Alert');
function logInToWeb(data): ThunkAction {
const {name, password} = data
Alert.alert(
`Hi, ${name} & ${password}`,
'möchten Sie sich ausloggen?',
[
{ text: 'Abbruch' },
{ text: 'Ausloggen' },
]
)
}
function skipLogin(): Action {
return {
type: 'SKIPPED_LOGIN',
};
}
function logOut(): ThunkAction {
...
}
function logOutWithPrompt(): ThunkAction {
....
}
module.exports = {logInToWeb, skipLogin, logOut, logOutWithPrompt};
So the Question is:
how can i pass the value of the Textinput from the LoginScreen.js on ButtonClick To the logInToWeb-Method in the login.js
How can i get the name and password in the alert that i called in login.js
Thats it. Later i will ask more about bearer-auth and loggin to server :)
I think what you're asking is how to send the name and password to your logIn() method? Maybe something like this would work:
// Login Button
<LoginButton
name={this.state.name}
password={this.state.password}
source="First screen" />
// Login method
async logIn() {
const {dispatch, onLoggedIn, name, password} = this.props;
this.setState({isLoading: true});
try {
await Promise.race([
dispatch(logInToWebk({name, password})),
timeout(15000),
]);
}
}
then
function logInToWebk(data): ThunkAction {
const { name, password } = data
// do something with name + password
}