Take picture, save and access Camera with react-native - javascript

I am studing react-native a 4 months and I am Build my App. I got problems with Camera. I am trying to take a picture, save and access the photo. I take a picture but I don't know where picture goes and how to acess.
I am using expo import camera, because when I use from react a get some error.
this is my code:
import React, {Component} from 'react';
import {Text, View, TouchableOpacity, Image,TouchableHighlight,Vibration} from 'react-native';
//import Camera from 'react-native-camera';
import {Camera, Permissions,} from 'expo';
const myStyle = {
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: 'red',
padding: 10,
margin: 40
},
main2: {
flex: 1,
//alignItems: 'flex-start',
flexDirection: 'row',
justifyContent: 'space-between',
},
main: {
flex: 1,
},
borda: {
//flex: 0.1,
alignItems: 'flex-end',
backgroundColor: 'black',
height: 110,
},
borda2: {
backgroundColor: 'black',
width: 60,
},
borda3: {
width: 60,
backgroundColor: 'black',
},
borda4: {
height: 120,
backgroundColor: 'black',
//flex: 1,
alignItems: 'center',
flexDirection: 'row',
justifyContent:'space-between',
},
texto:{
fontSize: 18,
marginBottom: 40,
color: 'white',
},
textoButton:{
fontSize: 18,
color: 'white',
marginTop: 5,
},
button:{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor:'transparent',
flexDirection: 'row',
justifyContent:'space-between'
},
cameraStyle:{
width: 70,
height: 57,
//margin:30,
alignItems: 'center',
tintColor: 'white',
},
flipStyle:{
width: 52,
height: 57,
marginLeft:10,
alignItems: 'center',
tintColor: 'white',
},
gallerystyle:{
width: 64,
height: 57,
marginLeft:10,
alignItems: 'center',
tintColor: 'white',
marginRight: 10,
},
closeStyle:{
width: 56,
height: 57,
marginTop: 30,
marginRight: 20,
alignItems: 'flex-end',
tintColor: 'white',
justifyContent:'flex-end'
},
box:{
width: 'auto',
justifyContent: 'space-between',
flexDirection: 'column',
alignItems: 'center',
},
};
export default class CameraAcess extends Component {
constructor(props) {
super(props);
this.state = {hasCameraPermission: null, type: Camera.Constants.Type.back,};
}
async componentWillMount() {
const {status} = await Permissions.askAsync(Permissions.CAMERA);
this.setState({hasCameraPermission: status === 'granted'});
}
snap = async function(){
if (this.camera) {
this.camera.takePictureAsync().then(data => {
FileSystem.moveAsync({
from: data,
to: '${FileSystem.documentDirectory}photos/Photo_${this.state .photoId}.jpg',
}).then(() => {
this.setState({
photoId: this.state.photoId + 1,
});
Vibration.vibrate();
})
.catch((e) => {
console.log(e, 'ERROR');
});
})
.catch((e) => {
console.log(e, 'takePicture ERROR');
});
}
console.log('I took the picture');
};
cameraPhoto = require('./Images/camera.png');
flipPhoto = require('./Images/flip.png');
closePhoto = require('./Images/close.png');
galleryPhoto = require('./Images/gallery.png');
render() {
const { main,main2, borda, borda2, borda3,borda4,cameraStyle,flipStyle,closeStyle,box,textoButton,gallerystyle} = myStyle;
const {hasCameraPermission} = this.state;
if (hasCameraPermission === null) {
return <View/>;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={main}>
<Camera style={main} type={this.state.type}>
<TouchableHighlight onPress={() => {this.props.navigator.push({id: 'MenuPrincipal'});}}
style={borda} underlayColor={'black'} activeOpacity={0.6}>
<Image source={this.closePhoto} style={[closeStyle]}/>
</TouchableHighlight>
<View style={main2}>
<View style={[borda2]}/>
<View style={[borda3]}/>
</View>
<View style={[borda4]}>
<TouchableOpacity onPress={() => {this.setState({type: this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front : Camera.Constants.Type.back,});}}>
<View style={box}>
<Image source={this.flipPhoto} style={[flipStyle]}/>
<Text style={textoButton}>
Flip
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {this.snap()}}>
<View style={box}>
<Image source={this.cameraPhoto} style={[cameraStyle]}/>
<Text style={textoButton}>
Capture
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {false}}>
<View style={box}>
<Image source={this.galleryPhoto} style={[gallerystyle]}/>
<Text style={textoButton}>
Gallery
</Text>
</View>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
}
}
Someone help me to solve this problem and please be especific and clearly in your explanation, every details are necessary to me. I need this to end my App.

If I were you I would do
console.log(data);
then you can see what the promise returns in the XDE. You should, at the very least, see the following properties: height, width, uri. Uri will show you exactly where that image is being stored in the cache.

Related

horizontal ScrollView is not scrolling

When adding horizontal={true} to my scrollview, I thought that would be enough to be able to scroll sideways. For some reason, even though there is enough content to scroll to, the images will not scroll continuously. If you copy and paste this code into snack.expo.io you will see what I mean.
I am not sure what is causing this issue, as I know the normal scrollview vertically works fine and scrolls like normal. I have also tried using nestedScrollenabled to true
Any insight at all is appreciated more than you know!
import React, { useState } from 'react';
import {Pressable, StyleSheet, Text, View, useWindowDimensions, Dimensions, Image, Animated, PanResponder,
TouchableOpacity, ScrollView, ImageBackground, Platform} from 'react-native';
import { SearchBar } from 'react-native-elements';
import {
scale,
verticalScale,
moderateScale,
ScaledSheet,
} from 'react-native-size-matters';
import { MaterialCommunityIcons } from '#expo/vector-icons';
const Images = [
{ id: '1', uri: require('./assets/snack-icon.png'), text: 'Test' },
{ id: '2', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
{ id: '3', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
{ id: '4', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
]
const pressableTest = () => {
let textlog = '';
const [state, setState] = useState(0);
};
export default class Home extends React.Component {
renderImagesHorizontal = () => {
return Images.map((item, i) => {
return (
<View
style={{
width : '150%',
paddingLeft: scale(10),
paddingRight: scale(10),
paddingBottom: scale(15),
}}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('VenueDetails')}>
<ImageBackground
source={item.uri}
style={{
width: '100%',
height: scale(225),
shadowColor: '#000',
shadowOffset: { width: 1, height: 4 },
shadowOpacity: 1,
}}
imageStyle={{ borderRadius: 10 }}>
<View
style={{
position: 'absolute',
bottom: 10,
left: 10,
justifyContent: 'flex-start',
alignItems: 'flex-start',
}}>
<Text style={styles.name}>Name</Text>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={styles.category}>Category</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.money}>$$</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.starRating}>★★★</Text>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
);
});
};
renderImagesVertical = () => {
return Images.map((item, i) => {
return (
<View style={{ paddingLeft: scale(10), paddingRight: scale(10), paddingBottom: scale(20) }}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('VenueDetails')}>
<ImageBackground
source={item.uri}
style={{ width:'100%', height: scale(125),
shadowColor: '#000',
shadowOffset: {width: 1, height: 7},
shadowOpacity: 1,}} imageStyle = {{ borderRadius: 20}}>
<View
style={{
position: 'absolute',
bottom: 10,
left: 10,
justifyContent: 'flex-start',
alignItems: 'flex-start',
}}>
<Text style={styles.name}>Name</Text>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={styles.category}>Category</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.money}>$$</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.starRating}>★★★</Text>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
);
});
};
state = {
search: '',
};
updateSearch = (search) => {
this.setState({ search });
};
render() {
const { search } = this.state;
return (
<ScrollView style={{ flex: 1, backgroundColor: '#272933', horizontal: 'true' }}>
<View style={{flexDirection:'row', marginTop: scale(20)}}>
{/*this will proabbly say somethign different and probably have a different look to it but you get the idea
I was also trying to add a shadow to this but couldnt figure it out. */}
<Text style={{marginTop: scale(30) ,fontSize: scale(40), fontWeight: 'bold', color: '#FFFFFF', paddingLeft: scale(20)}}>
Home
</Text>
<View style={{paddingTop: scale(40), paddingLeft: scale(155)}}>
</View>
</View>
<SearchBar
placeholder="Search..."
onChangeText={this.updateSearch}
value={search}
round='true'
containerStyle={{backgroundColor: '#272933', borderBottomColor: 'transparent', borderTopColor: 'transparent',
paddingLeft: scale(20) , paddingRight: scale(20)}}
inputContainerStyle={{height: scale(30), width: scale(310), backgroundColor: '#3A3B3C'}}
searchIcon={() => <MaterialCommunityIcons name="glass-mug-variant" size={25} color='#87909A'/>}
clearIcon= 'null'
/>
<ScrollView
horizontal={true}
>
<View style={{ flex: 1, flexDirection : 'row', marginTop: 15 }}>{this.renderImagesHorizontal()}</View>
</ScrollView>
<View style={{ flex: 1, marginTop: 15 }}>{this.renderImagesVertical()}</View>
</ScrollView>
);
}
}
const styles = ScaledSheet.create({
starRating: {
color: 'white',
fontSize: '20#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
category: {
color: 'white',
fontSize: '20#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
name: {
fontWeight: 'bold',
color: 'white',
fontSize: '25#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
dot: {
color: 'white',
fontSize: '5#s',
paddingLeft: '5#s',
paddingRight: '5#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
money: {
color: 'white',
fontSize: '20#s',
},
});
in android you must add nestedScrollEnabled={true} to Enables nested scrolling for Android API level 21+. see here
<ScrollView>
<ScrollView nestedScrollEnabled={true}>
</ScrollView>
</ScrollView>
try snack here (test in android & ios not web)

react native : How can TouchableOpacity be displayed or hidden according to the conditions?

How can TouchableOpacity be displayed or hidden according to the conditions?
How TouchableOpacity can be viewed or hidden depending on the conditions
Only if the Sampling_Method_Description field is not null then TouchableOpacity should be displayed otherwise not displayed.
<TouchableOpacity
style={{
height: 50,
width: 50,
borderRadius: 5,
borderColor: 'black',
borderWidth: 2,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'red',
left: 120,
top: 7,
}}
onPress={() => {
console.log('EYE PRESSED!!')
}}
>
<MaterialIcons
size={40}
name='visibility'
/>
</TouchableOpacity>
You can use ternary operator inside JSX block like so:
return (
<View>
{yourConditionIsTrue?
<TouchableOpacity
style={{
height: 50,
width: 50,
borderRadius: 5,
borderColor: 'black',
borderWidth: 2,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'red',
left: 120,
top: 7,
}}
onPress={() => {
console.log('EYE PRESSED!!')
}}
>
<MaterialIcons
size={40}
name='visibility'
/>
</TouchableOpacity>
:
null }
</View>
)
import React, {useState} from "react";
import { View } from "react-native";
Example = () => {
const [showButton, setshowButton] = useState(false);
const renderButton = () => {
return showButton ? (
<TouchableOpacity
style={{
height: 50,
width: 50,
borderRadius: 5,
borderColor: "black",
borderWidth: 2,
alignItems: "center",
justifyContent: "center",
backgroundColor: "red",
left: 120,
top: 7,
}}
onPress={() => {
console.log("EYE PRESSED!!");
}}>
<MaterialIcons size={40} name="visibility" />
</TouchableOpacity>
) : null;
};
return <View>{renderButton()}</View>;
};
You can simply use the && operator :
{Sampling_Method_Description &&
<TouchableOpacity
//other props
//...
//...
/>}

Make Search using firebase in react native

I am new to react native and firebase. I want to make a search bar that can search all data from firebase according to Barcode value, but I'm facing some errors while doing it. I think that my code is wrong somewhere but don't know where. I have transferred the firebase credentials to dbConfig.js . Here is my firebase data firebase data and my code:
import React,{Component} from 'react';
import { View, Text,TextInput,StyleSheet,Image, Button} from 'react-native';
import firebase from './dbConfig';
export default class ListItem extends Component {
render() {
return (
<>
<View style={styles.BackGround}>
<View style={styles.SectionStyle}>
<Image
source={require('./mic.png')} //mic image here
style={styles.ImageStyle}
/>
<TextInput
style={{ flex: 1, justifyContent: 'center', textAlign: 'center', fontSize: 12}}
placeholder="Search for Product"
underlineColorAndroid="transparent"
//onChangeText={(text) => this.setState({data: text})}
onSubmitEditing = {(text)=> this.setState({data: text})}
value = {this.state.data}
// onSubmitEditing={()=>this._search}
//onSubmitEditing={()=>this.componentWillMount}
/>
<Image
source={require('./usr.png')} //icon image here
style={styles.ImageStyle2}
/>
</View>
<View>
<Text>{this.state.items}</Text>
</View>
</View>
</>
);
}
constructor(props){
super(props);
this.state= {
items: '',
data: '',
};
}
componentWillMount(){
var ref = firebase.database().ref('/');
ref.child(this.state.data).on("value", snapshot =>{
console.log(snapshot.val().info.Price);
//if(snapshot.val().Price == this.state.data){
//this.setState({items: Object.values(snapshot.val())});
//}
//else{
//alert('there is problem');
//}
});
}
}
const styles = StyleSheet.create({
BackGround: {
backgroundColor: '#22abb6',
height: '100%'
},
SectionStyle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
// borderWidth: 0.8,
// borderColor: '#000',
shadowColor:'#176f75',
marginTop: 50,
height: 40,
borderRadius: 10,
margin: 10,
},
ImageStyle: {
padding: 10,
marginLeft: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
},
ImageStyle2: {
padding: 10,
marginLeft: 10,
marginRight: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
},
});
I did it by changing the follows:
//adding this in TextInput
onSubmitEditing = {this.componentWillMount}
//on changing the function compoundWillMount to async()
componentWillMount= async()=>{

React Native app works on iOS but comes up with error on Android posts.map not defined

I have created a simple program to display information from my website on the app. It works on iOS but on my Android device an error shows up :
posts.map is not a function. This is my code:
import React, { Component } from 'react';
import {
View,
Text,
ActivityIndicator,
ScrollView,
StyleSheet,
Image,
Header,
} from 'react-native';
let lw = 100;
import Img from 'react-image';
let li = 'https://www.teanewsnetwork.com/profileicons/';
let bean = 'azure.jpg';
export default class App extends Component {
state = {
loading: true,
error: false,
posts: [],
};
componentWillMount = async () => {
try {
const response = await fetch(
'https://www.teanewsnetwork.com/api/fetcharticles.php?code=#NIL7*GKD60JTRTEFZ0CkvpHMJJW^-9q&starting=0&limit=40'
);
const posts = await response.json();
this.setState({ loading: false, posts });
} catch (e) {
this.setState({ loading: false, error: true });
}
};
renderPost = ({ id, title, content, authorimage, authorname }, i) => {
let b = { authorname };
return (
<View style={styles.postContent}>
<View
style={{
flex: 1,
flexDirection: 'column',
textAlign: 'center',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={styles.postauthor}>{title} </Text>
<Image
source={{
uri: `https://teanewsnetwork.com/profileicons/${authorimage}`,
}}
defaultSource={require('./contact-outline.png')}
style={{
width: lw,
height: lw,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
borderRadius: lw / 2,
}}
/>
<Text style={styles.postauthor}>{authorname}</Text>
</View>
<Text style={styles.postBody}>{content}</Text>
</View>
);
};
render() {
const {posts, loading, error} = this.state
if (loading) {
return (
<View style={styles.center}>
<ActivityIndicator animating={true} />
</View>
)
}
if (error) {
return (
<View style={styles.center}>
<Text>
Failed to load posts!
</Text>
</View>
)
}
return (
<ScrollView style={styles.container}>
{posts.map(this.renderPost)}
</ScrollView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
borderBottomWidth: 0,
borderBottomColor: 'red',
top: 100,
zIndex: 6,
},
postauthor: {
flex: 1,
borderBottomWidth: 0,
borderBottomColor: 'red',
paddingVertical: 25,
fontSize: 18,
paddingRight: 15,
left: 10,
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
},
postContent: {
flex: 1,
borderBottomWidth: 20,
borderBottomColor: '#EEE',
borderRadius: 4,
fontSize: 18,
left: 0,
paddingRight: 15,
justifyContent: 'center',
alignItems: 'center',
textAlignVertical: 'center',
textAlign: 'center',
},
postBody: {
marginTop: 1,
fontSize: 18,
color: 'black',
left: 10,
textAlign: 'center',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
I am a beginner coder on react native and would like to have some help here. The code works on iOS emulator with EXPO but doesnt work on my Android Device.
Thanks in Advance!
Most likely posts is not a array, check the type of posts.

Invisible Margin on react-native-scrollable-tab-view

There seems to be a un-changeable margin on views using the react-native-scrollable-tab-view module. I can seem to get my code to fit to page on the views nested inside the scrollable-tab-view component. Any ideas? here's the code of the page presented:
'use strict';
import React from 'react';
import {
StyleSheet,
View,
Image,
Text,
TextInput
} from 'react-native';
//dimensions
var Dimensions = require('Dimensions');
var window = Dimensions.get('window');
//modules/pages
var StepImage = require('../components/StepImage');
import Icon from 'react-native-vector-icons/FontAwesome';
import {Actions} from "react-native-router-flux";
var NavHeader = require('../components/Header');
var UserStat = require('../components/UserStat');
var UserCircle = require('../components/UserCircle');
var Button = require('../components/Button');
var Data = require('../stores/userDiets');
var NavigationBar = require('react-native-navbar');
var Profile = React.createClass({
getInitialState: function() {
return {
};
},
render: function() {
var Keywords = Data.diets;
return (
<View style={[styles.container]}>
<NavigationBar
style={{width: window.width}}
tintColor={'#50AE57'}
title={{title: 'Robert Greenfield', tintColor: 'white', style: {fontFamily: 'Nunito', fontSize: 18}}} />
<View style={[styles.header, this.border('red')]}>
<View style={[styles.userrow, this.border('red')]}>
<UserCircle source={require('../img/user/user.jpg')} style={styles.circle}/>
<View style={[styles.userinfo, this.border('orange')]}>
<View style={[styles.userstats, this.border('blue')]}>
<UserStat stat={3333} statTitle={'posts'} />
<UserStat stat={8888} statTitle={'achievements'} />
<UserStat stat={112} statTitle={'following'} />
<UserStat stat={'550K+'} statTitle={'followers'} />
</View>
<Icon.Button size={12} name="cogs" style={styles.edit} backgroundColor="#F4F4F4" onPress={this.loginWithFacebook}>
<Text style={styles.editText}>Edit Profile</Text>
</Icon.Button>
</View>
</View>
<View style={[styles.userBio, this.border('blue')]}>
<Text style={styles.userBioText}>The biggest #nutfree IG in the world. tag #nutfreenoms or #nomsy. To be featured, make an account at nomsy.co and post what you want shown! nomsy.co</Text>
</View>
<View style={styles.dietRow}>
{this.renderDiets(Keywords)}
</View>
</View>
</View>
);
},
renderDiets: function(diets) {
var that = this;
return diets.map(function(diet, i) {
return <View key={i} style={styles.box}><Text key={i} style={styles.userBioText}>{diet.name}</Text></View>
});
},
border: function(color) {
return {
//borderColor: color,
//borderWidth: 1,
}
}
});
var styles = StyleSheet.create({
box: {
margin: 2,
backgroundColor: '#56bf60',
borderRadius:2,
height: window.height/35,
padding: 3,
justifyContent: 'center'
},
dietRow:{
flexWrap: 'wrap',
flexDirection:'row',
height: window.height/20,
marginLeft: window.width/40,
width: window.width*0.96,
},
userBio: {
width: window.width*0.96,
alignItems: 'center',
marginLeft: window.width/80,
marginBottom: window.height/100
},
userBioText: {
color: 'black',
fontFamily: 'Nunito',
fontSize: 10
},
editText: {
color: 'white',
fontFamily: 'Nunito',
alignSelf: 'center'
},
edit: {
height: window.height/25,
justifyContent: 'center',
alignItems: 'center'
},
circle: {
width: window.width/5,
height: window.width/5,
borderRadius: window.width/10
},
userstats: {
flexDirection: 'row',
backgroundColor: 'white',
justifyContent: 'space-around',
marginBottom: window.height/100
},
userinfo: {
flexDirection: 'column',
backgroundColor: 'transparent',
width: window.width/1.4
},
userrow: {
flexDirection: 'row',
backgroundColor: 'transparent',
height: window.height/8,
justifyContent: 'space-around',
width: window.width
},
header: {
marginTop: window.height/50,
width: window.width,
flex: 0.9,
backgroundColor: 'white',
},
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'flex-start',
},
});
module.exports = Profile;
And here's what it looks like:
You have to set automaticallyAdjustContentInsets={false} in your ListView (or ScrollView). Details here:
https://github.com/skv-headless/react-native-scrollable-tab-view/pull/174
https://github.com/facebook/react-native/issues/721
https://facebook.github.io/react-native/docs/scrollview.html#automaticallyadjustcontentinsets

Categories