Picker in react native is showing an error - android

I am trying to fetch data from firebase database and show it in a Picker. This project fetch data from firebase Database table named category and show it in a React native picker. But picker showing an Error. I tried so many solutions, but the problem only key or value will be fetched from the db. I want both
This is my Firebase Db. And below is my code
import React from 'react';
import { StyleSheet, Text, View, TextInput, Picker } from 'react-native';
import DateTimePicker from 'react-native-modal-datetime-picker';
import moment from 'moment';
import * as firebase from 'firebase';
import {firebaseConfig} from './ApiKeys';
if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig); }
console.ignoredYellowBox = ['Setting a timer',];
var pickerArr = [];
export default class App extends React.Component {
constructor(props){
super(props)
this.state=({
isDateTimePickerVisible: false,
selecteddate:'Date',
category:0,
snapshotList:{},
})
}
componentDidMount() {
this._loadInitialState();
}
_loadInitialState = () => {
//====================================
firebase.database().ref('/category').once('value').then((snapshot)=> {
this.setState({category:snapshot})
console.log(this.state.category);
})
//====================================
};
loadUserTypes() {
var snapshot = this.state.category;
snapshot.forEach(userSnapshot => {
var k = userSnapshot.key;
var name = userSnapshot.val();
pickerArr.push(<Picker.Item label={userSnapshot.key} value={userSnapshot.val()}/>);
console.log("k="+ k +" "+"name="+name); //Showing Data correctly
});
return pickerArr;
}
_showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true });
_hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false });
_handleDatePicked = (pickeddate) => {
day = pickeddate.getDate();
month = pickeddate.getMonth();
year = pickeddate.getFullYear();
console.log('A date has been picked: ' + day + '-' + month + '-' + year);
exdate= moment(pickeddate).format('HH:mm')
this.setState({selecteddate : exdate})
this._hideDateTimePicker();
console.log("cat "+ this.state.category.val())
};
onFocus = () => {
this._handleDatePicked();
}
render() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<Text
onPress={ () => this._showDateTimePicker() }
value={this.state.selecteddate}
>{this.state.selecteddate}</Text>
{/* //--------------------------------------DateTimePicker */}
<DateTimePicker
isVisible={this.state.isDateTimePickerVisible}
onConfirm={this._handleDatePicked}
onCancel={this._hideDateTimePicker}
mode={'time'}
datePickerModeAndroid={'spinner'}
/>
{/* //-------------------------------------- */}
<Picker
selectedValue={this.state.language}
style={{height: 50, width: 100}}
onValueChange={(itemValue, itemIndex) =>
this.setState({language: itemValue})
}>
{/* -------------------Dynamic Picker Data------------------ */}
<Picker.Item label='Salle de sport' value='default'/>
{this.loadUserTypes()}
{/* -------------------------------------------------------- */}
</Picker>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

Related

How do you save photos with a set height and width?

I am creating a feature to capture pictures with a height/width set and save them in the gallery. At my current stage I can take a photo and save it to the gallery, the only problem is that the saved photo is not the height and width I previously set.
It seems like something simple, but I don't know what I am overlooking.
App.js
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, SafeAreaView, Image, TouchableOpacity } from 'react-native';
import { useEffect, useRef, useState } from 'react';
import { FontAwesome } from "#expo/vector-icons";
import { Camera } from 'expo-camera';
import { shareAsync } from 'expo-sharing';
import * as MediaLibrary from 'expo-media-library';
import styles from "./styles.js";
export default function App() {
let cameraRef = useRef();
const [hasCameraPermission, setHasCameraPermission] = useState();
const [hasMediaLibraryPermission, setHasMediaLibraryPermission] = useState();
const [photo, setPhoto] = useState();
useEffect(() => {
(async () => {
const cameraPermission = await Camera.requestCameraPermissionsAsync();
const mediaLibraryPermission = await MediaLibrary.requestPermissionsAsync();
setHasCameraPermission(cameraPermission.status === "granted");
setHasMediaLibraryPermission(mediaLibraryPermission.status === "granted");
})();
}, []);
if (hasCameraPermission === undefined) {
return <Text>Requesting permissions...</Text>
} else if (!hasCameraPermission) {
return <Text>Permission for camera not granted. Please change this in settings.</Text>
}
let takePic = async () => {
let options = {
quality: 1,
base64: true,
exif: false
};
};
if (photo) {
let savePhoto = () => {
MediaLibrary.saveToLibraryAsync(photo.uri).then(() => {
setPhoto(undefined);
});
};
return (
<SafeAreaView style={styles.container}>
<Image style={styles.responsiveImage} source={{ uri: "data:image/jpg;base64," + photo.base64 }} resizeMode="contain"/>
{hasMediaLibraryPermission ?
<TouchableOpacity style={styles.buttonSave} onPress={savePhoto}>
<FontAwesome name="save" size={23} color="#fff"></FontAwesome>
</TouchableOpacity> : undefined}
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container}>
<Camera style={styles.camera} ref={cameraRef}>
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.buttonCamera} onPress={takePic}>
<FontAwesome name="camera" size={27} color="#fff"></FontAwesome>
</TouchableOpacity>
</View>
<StatusBar style="auto" />
</Camera>
</SafeAreaView>
);
}
style.js
import { StyleSheet } from "react-native"
const styles = StyleSheet.create({
responsiveImage: {
width: '80%',
height: 400,
},
});
export default styles

Android problem with expo-google-app-auth

I have a problem with expo-google-app-auth in Android. It's work perfectly fine with IOS.
After successful sign in in Android instead of redirect me back to my app LoggedInPage component, I'm again in LoginPage component. I think it's because Android opens application again and I'm losing the state, so I'm also losing the states from login and I have to sign in again...
In IOS it just sign me in an redirecting to LoggedInPage component perfectly..
import React, { useState } from "react";
import * as Google from "expo-google-app-auth";
import { StyleSheet, Text, View, Image, Button } from "react-native";
export default function App() {
const [signedIn, setSignIn] = useState(false);
const [name, setName] = useState("");
const [photoUrl, setPhotoUrl] = useState("");
signIn = async () => {
try {
console.log("Sign in 1");
const result = await Google.logInAsync({
androidClientId:
“<< android client id >>apps.googleusercontent.com",
iosClientId:
“<< iOS client id >>.apps.googleusercontent.com",
scopes: ["profile", "email"]
});
console.log("Sign in 2");
console.log("Result: ", result);
if (result.type === "success") {
setSignIn(true);
setName(result.user.name);
setPhotoUrl(result.user.photoUrl);
return result.accessToken;
} else {
return { cancelled: true };
}
} catch (e) {
return { error: true };
}
};
const LoginPage = () => {
console.log("Inside LoginPage");
return (
<View>
<Text style={styles.header}>Sign In With Google</Text>
<Button title="Sign in with Google" onPress={() => signIn()} />
</View>
);
};
const LoggedInPage = () => {
return (
<View style={styles.container}>
<Text style={styles.header}>Welcome:{name}</Text>
<Image style={styles.image} source={{ uri: photoUrl }} />
</View>
);
};
console.log("SignedIn: ", signedIn);
return (
<View style={styles.container}>
{signedIn ? <LoggedInPage /> : <LoginPage />}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
},
header: {
fontSize: 25
},
image: {
marginTop: 15,
width: 150,
height: 150,
borderColor: "rgba(0,0,0,0.2)",
borderWidth: 3,
borderRadius: 150
}
});
Any ideas/guidance how should I fix my app in Android ?
You need to add a redirectUrl:
const result = await Google.logInAsync({
androidClientId:
“<< android client id >>apps.googleusercontent.com",
iosClientId:
“<< iOS client id >>.apps.googleusercontent.com",
scopes: ["profile", "email"],
redirectUrl: "{Your Bundle ID (com.example.app)}:/oauth2redirect/google",
});

Camera is not running

I’m trying to make a prototype application that over and over
1- record a video with the camera for x seconds
2- displays this video
For this I use the components Camera from expo-camera and Video from expo-av
For this I have two views :
I use in my code the stateSequence property and the sequencer() function which displays alternately the view with the Camera component which films for x seconds , and the video view which allows me to display the video.
Sequencer() is triggered with setInterval( this.sequencer , 10000) found in the componentWillMount()
I can switch alternately from a View with the Camera component to a View with the Video component.
To record a video with the Camera component I use recordAsync(), but I get the following error:
Unhandled promise rejection: Error: Camera is not running
I’m using an android phone for my tests.
Can’t you help me
this is my code
import { StyleSheet, Text, View ,TouchableOpacity} from 'react-native';
import * as Permissions from 'expo-permissions';
import { Camera } from 'expo-camera';
import { Video } from 'expo-av';
import { Logs } from 'expo';
export default class SequenceViewer extends Component {
constructor(props) {
super(props);
this.state = {
stateSequence: "SHOOT ",
hasCameraPermission: null,
type: Camera.Constants.Type.front,
}
this.recordVideo = this.recordVideo.bind(this)
}
sequencer = () => {
if(this.state.stateSequence==="WATCH"){
this.setState({ stateSequence: "SHOOT",})
this.recordVideo(); // Error message Camera is not running
} else {
this.setState({stateSequence: "WATCH"})
}
}
async componentWillMount() {
let rollStatus = await Permissions.askAsync(Permissions.CAMERA_ROLL);
let cameraResponse = await Permissions.askAsync(Permissions.CAMERA)
if (rollStatus.status=='granted'){
if (cameraResponse.status == 'granted' ){
let audioResponse = await Permissions.askAsync(Permissions.AUDIO_RECORDING);
if (audioResponse.status == 'granted'){
this.setState({ permissionsGranted: true });
setInterval( this.sequencer , 10000);
}
}
}
}
recordVideo = async () => {
if(this.state.cameraIsRecording){
this.setState({cameraIsRecording:false})
this.camera.stopRecording();
}
else {
this.setState({cameraIsRecording:true})
if (this.camera) {
let record = await this.camera.recordAsync(quality='480p',maxDuration=5,mute=true).then( data =>{
this.setState( {recVideoUri :data.uri})
})
}
}
};
render() {
const { hasCameraPermission } = this.state
if(this.state.stateSequence=="WATCH")
{
return(
<View style={styles.container}>
<Video
source={{ uri:this.state.recVideoUri }}
rate={1.0}
volume={1.0}
isMuted={false}
resizeMode="cover"
shouldPlay
isLooping
style={{ width: 300, height: 300 }}
ref={(ref) => { this.player = ref }}
/>
</View>
)
} else
{
return(
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={this.state.type} ref={ref => {this.camera = ref; }}></Camera>
</View>
)
}
}
}
const styles = StyleSheet.create({
viewerText: {
fontSize: 20,
fontWeight: 'bold',
},
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Thank you
I had the same problem, my solution was by default camera type have to be "back" and you could change to "front" by:
componentDidMount = () => {
this.props.navigation.addListener('didFocus', async () => {
await setTimeout(() => {
this.setState({ cameraType: Camera.Constants.Type.front })
}, 100)
});
}
I was getting the "Camera is not running" error when i changed screens. So for functional components instead of withNavigationFocus(Camera) use this method:
import { useIsFocused } from '#react-navigation/native';
function MyComponent() {
const isFocused = useIsFocused()
return (
<View>
{ isFocused && <RNCamera /> }
</View>
)
}

React native Image uploading not uploading the images

I am developing an app That contain an image uploader. I found some code on internet that can upload image. And it worked partially. Which means When i press the choose image button, it opens gallery and i am able to select and crop image. And after cropping when i select ok nothing happen. It just show the image and its not uploading to the firebase cloud. Here is my code.
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button,
Image,
ActivityIndicator,
TouchableOpacity
} from 'react-native';
import * as firebase from 'firebase';
import RNFetchBlob from 'react-native-fetch-blob';
import ImagePicker from 'react-native-image-crop-picker';
export default class RNF extends Component {
constructor (props) {
super(props);
this.state = {
loading: false,
dp: null
};
}
openPicker () {
this.setState({ loading: true });
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
// const { uid } = this.state.user
const uid = '12345';
ImagePicker.openPicker({
width: 300,
height: 300,
cropping: true,
mediaType: 'photo'
}).then(image => {
const imagePath = image.path;
let uploadBlob = null;
const imageRef = firebase.storage().ref(uid).child('dp.jpg');
let mime = 'image/jpg';
fs.readFile(imagePath, 'base64')
.then((data) => {
// console.log(data);
return Blob.build(data, { type: `${mime};BASE64` });
})
.then((blob) => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: mime });
})
.then(() => {
uploadBlob.close();
return imageRef.getDownloadURL();
})
.then((url) => {
let userData = {};
// userData[dpNo] = url
// firebase.database().ref('users').child(uid).update({ ...userData})
let obj = {};
obj['loading'] = false;
obj['dp'] = url;
this.setState(obj);
})
.catch((error) => {
console.log(error);
});
})
.catch((error) => {
console.log(error);
});
}
render () {
const dpr = this.state.dp ? (<TouchableOpacity onPress={ () => this.openPicker() }><Image
style={{ width: 100, height: 100, margin: 5 }}
source={{ uri: this.state.dp }}
/></TouchableOpacity>) : (<Button
onPress={ () => this.openPicker() }
title={ 'Change Picture' }
/>);
const dps = this.state.loading ? <ActivityIndicator animating={this.state.loading} /> : (<View style={styles.container}>
<View style={{ flexDirection: 'row' }}>
{ dpr }
</View>
</View>);
return (
<View style={styles.container}>
{ dps }
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5
}
});
AppRegistry.registerComponent('RNF', () => RNF);

I want to use the data from a JSON file as the label for my radio button (react native)

I have an app that reads a JSON file. In one tab I have it coming out as a list, on another tab, I want it to show the items selected from the file as the labels for a radio button I found here:
https://www.npmjs.com/package/react-native-radio-buttons-group
Here's the code that I have for the tab of my app that pulls names of medications from a JSON file:
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TouchableHighlight,
FlatList
} from "react-native";
import { Icon } from 'native-base'
import RadioGroup from 'react-native-radio-buttons-group';
//import MultipleChoice from 'react-native-multiple-choice'
class LikesTab extends Component {
_onSelect = ( item ) => {
console.log(item);
};
onPress = data => this.setState({ data });
constructor(props){
super(props);
this.state = {
data:[]
}
}
//SETTING THE STATE MAKING AN EMPTY ARRAY WHICH WE FIL
// state = {
// data: []
//};
componentWillMount() {
this.fetchData();
}
//Getting the data
fetchData = async () => {
const response = await fetch("https://api.myjson.com/bins/s5iii");
const json = await response.json();
this.setState({ data: json.results });
};
//var customData = require('./customData.json');
//Setting what is shown
render() {
return (
<View style={{ marginVertical: 10, backgroundColor: "#E7E7E7" }} >
<FlatList
data={this.state.data}
keyExtractor={(x, i) => i}
renderItem={({ item }) =>
<Text>
{`${item.name.first} ${item.name.last}`}
</Text>}
/>
</View>
);
}
}
export default LikesTab;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});
Here's my tab for the radio button
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import RadioGroup from 'react-native-radio-buttons-group';
export default class AddMediaTab extends Component {
componentWillMount() {
this.fetchData();
}
//Getting the data
fetchData = async () => {
const response = await fetch("https://api.myjson.com/bins/s5iii");
const json = await response.json();
this.setState({ data: json.results });
};
state = {
data: [
{
label:' ' ,
}
]
};
// update state
onPress = data => this.setState({ data });
render() {
let selectedButton = this.state.data.find(e => e.selected == true);
selectedButton = selectedButton ? selectedButton.value : this.state.data[0].label;
return (
<View style={styles.container}>
<Text style={styles.valueText}>
Value = {selectedButton}
</Text>
<RadioGroup radioButtons={this.state.data} onPress={this.onPress}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
valueText: {
fontSize: 18,
marginBottom: 50,
},
});
What is your selectedButton variable? I think Value = {selectedButton} is the issue. If selectedButton evaluates to a string, fine but it looks like it is an object in your case. Array.find() returns the first element that satisfies the condition, or if none satisfy it it returns undefined. If that variable undefined during the time it's waiting for your api call to return something that could cause an issue as well.

Categories

Resources