I have created a react-native app in VS Code. The app is running fine in the browser with expo. Generated a keystore file and created an .apk with gradlew assembleRelease.
The .apk can be installed on my Android tablet. But after starting the app, it is not running and the splash screen is shown (see image below).
The SDK version on the tablet (30) is higher than the minSdkVersion (21) of the app.
Also added <uses-feature android:name="android.hardware.telephony" android:required="false" /> to the AndroidManifest.xml file.
Code is as follows.
index.js:
import { registerRootComponent } from 'expo';
import App4 from './App4';
// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
// It also ensures that whether you load the app in Expo Go or in a native build,
// the environment is set up appropriately
registerRootComponent(App4);
App4.js:
import React from 'react'
import List from './List.js'
const App = () => {
return (
<List />
)
}
export default App
List.js:
import React, { Component } from 'react'
import { Text, View, TouchableOpacity, StyleSheet, Image } from 'react-native'
class List extends Component {
state = {
products: []
}
componentDidMount() {
this.GetAllProducts();
}
GetAllProducts() {
//fetch("http://192.168.2.14:3000/getallproducts")
fetch("https://categoriesexpress444.herokuapp.com/getallproducts")
.then(res => res.json())
.then(jsonresult => {
this.setState({
products: jsonresult
});
console.log(this.state.products);
});
}
getsrcPath(string) { // this function distinguishes between images in UserImages folder and images on Cloudinary
var firstChar = string.charAt(0);
if (firstChar == '~') { // image is in UserImages folder and item.picture path starts wih ~/UserImages/
return string.substring(1, string.length);
}
else { // image is at Cloudinary and item.picture starts with http://
return string;
}
}
render() {
return (
<View>
{
this.state.products.map((item, index) => (
<TouchableOpacity
key = {item.id}
style = {styles.container}>
<Text style = {styles.text}>{item.productname}</Text>
<Text>{item.description}</Text>
<Text>€ {item.price}</Text>
<img src={this.getsrcPath(item.picture)} />
<Text style = {styles.text}>
{item.name}
</Text>
</TouchableOpacity>
))
}
</View>
)
}
}
export default List
const styles = StyleSheet.create ({
container: {
padding: 10,
marginTop: 3,
backgroundColor: '#ffffff',
alignItems: 'center',
cursor: 'none'
},
text: {
color: '#4f603c'
}
})
If you are using expo to create react native app then
you have to build an app over the expo using this command
expo build:adroid or expo build:ios
once the build will successfully create you will get one URL then you can use the URL to install the app on your device.
If you are using react-native-cli to create react native app then
you have to build an app over the expo using this command
./gradlew assembleRelease or ./gradlew assembleDebug in MacOs
Related
I'm trying to open up an external app from my react native app, but it only seems to be working on my iPhone and not my Android. The console.log shows "isInstalled false" for Android but "isInstalled True" for iPhone.
I want the react native app to check if the user has the external app installed on their phones already. If so, open the external app, and if not, the app will redirect the user to Google Play (Android) / App Store (iOS).
import { Linking, Platform } from 'react-native';
import { Header, Card } from 'react-native-elements';
import { SafeAreaView } from 'react-native-safe-area-context';
import { AppInstalledChecker } from 'react-native-check-app-install';
export default function App() {
return (
<SafeAreaView style={styles.container}>
<Card containerStyle={styles.cardStyle}>
<Card.Image
style={styles.image}
source={{
uri:"https://play-lh.googleusercontent.com/T0OPODRs2EciPVEwUHv4Xucn5_MMQ8pHzEII1THqiIa8ef3XaZ1rf-TWW1g10SvJ0w=s180-rw"
}}
onPress={()=>{
const iOSAppStoreUrl = 'https://apps.apple.com/sg/app/hdb-health/id1266210350'
const iOSGoogleStoreUrl = 'https://play.google.com/store/apps/details?id=com.hdb.healthAnd'
if( Platform.OS === 'ios'){
AppInstalledChecker
.checkURLScheme('hdbhealth')
.then((isInstalled) => {
Linking.openURL('hdbhealth://app')
})
.catch(Linking.openURL(iOSAppStoreUrl))
} else { // Android
AppInstalledChecker
.checkURLScheme('com.hdb.healthAnd')
.then((isInstalled) => {
Linking.openURL('hdbhealth://app')
})
.catch(Linking.openURL(iOSGoogleStoreUrl))
}
}}
/>
</Card>
</SafeAreaView>
);
}
You should use isAppInstalledAndroid instead of checkURLScheme for android.
https://github.com/redpandatronicsuk/react-native-check-app-install
I am trying to get some position information from a device, I am using React-native, Expo, and ExpoGo on android mobile, I am not using simulators, the application is working with ExpoGo on Android, but geolocation is not working, it sends this error message every time:
window.navigator.geolocation.getCurrentPosition is not available. Import and execute installWebGeolocationPolyfill() from expo-location to add it, or use the expo-location APIs instead.
Please help me find the solution to this issue.
This is the App code used:
import { Text, View} from "react-native";
import styles from "./styles";
const API_KEY = "";
const URL = `https://maps.google.com/maps/api/geocode/json?key=${API_KEY}&latlng=`;
export default function WhereAmI() {
const [address, setAddress] = useState("loading...");
const [longitude, setLongitude] = useState();
const [latitude, setLatitude] = useState();
useEffect(() => {
function setPosition({ coords: { latitude, longitude } }) {
setLongitude(longitude);
setLatitude(latitude);
fetch(`${URL}${latitude},${longitude}`)
.then(
(resp) => resp.json(),
(e) => console.error(e)
)
.then(({ results }) => {
setAddress(results[0].formatted_address);
});
}
navigator.geolocation.getCurrentPosition(setPosition);
let watcher = navigator.geolocation.watchPosition(
setPosition,
(err) => console.error(err),
{ enableHighAccuracy: true }
);
return () => {
navigator.geolocation.clearWatch(watcher);
};
});
return (
<View style={styles.container}>
<Text style={styles.label}>Address: {address}</Text>
<Text style={styles.label}>Latitude: {latitude}</Text>
<Text style={styles.label}>Longitude: {longitude}</Text>
</View>
);
}
I fixed this problem, and this worked for me.
geolocation on iOS and Android:
I installed the expo-location package by running expo install expo-location.
I imported expo location in App.js as Location: import * as Location from 'expo-location'.
I used the #installWebGeolocationPolyfill function that polyfills #navigator.geolocation for interop with the core React Native
and Web API approach to geolocation just before using of the #navigator.geolocation.getCurrentPosition like
this:
# ... some code
Location.installWebGeolocationPolyfill()
navigator.geolocation.getCurrentPosition(setPosition);
# ... some code
2.The error 'formatted_address' is undefined:
That because there is no API_KEY, you should get an API key from Google, instead, I just Added it manually into the #setPosition function like this:
#...some code
.then(
({ results }) => {
results[0]={formatted_address:"here"}
setAddress(results[0].formatted_address)
},
#...some code
In my react-native project I'd like to generate barcode from given value. I found react-native-barcode-builder but I don't know how to use this library in android correctly. I've already install by npm install --save react-native-barcode-builder but when I want to import library in project I have following error:
undefined is not an object (evaluating 'undefined.hex')
I think I should link this library by react-native link but it doesn't change anything. Every sample is for Xcode, but I developing on Windows in WebStorm. Can anyone tell me how to correctly use this library?
This is my code:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Barcode from 'react-native-barcode-builder'
import Dimensions from 'Dimensions';
import {
StyleSheet,
View,
Image
} from 'react-native';
const DEVICE_WIDTH = Dimensions.get('window').width;
const DEVICE_HEIGHT = Dimensions.get('window').height;
class CardDetailsScreen extends Component {
render() {
return (
<View style={styles.container}>
<Image source={this.props.imageSource} style={styles.image}/>
<Barcode value="Hello world" format="EAN-13"/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
image: {
width: DEVICE_WIDTH,
height: 250,
}
});
const mapStateToProps = (state) => {
return {
card: state.card
};
};
const mapDispatchToProps = (dispatch) => {
return {
getCardData() {
console.log('test');
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(CardDetailsScreen);
Here you've got the answer: https://devhub.io/repos/wonsikin-react-native-barcode-builder
Before use react-native-barcode-builder run: npm install react-native-svg --save && react-native link react-native-svg and it should works.
If you want to test a library that creates EAN13 natively you may try react-native-barcode-creator:
npm install react-native-barcode-creator && cd ios && pod install
I'm using react-native-fs to download a file(pdf, word, excel, png etc.) and I need to open it in other application. Is it possible to open downloaded file with Linking or better open a dialog with possible apps like when using Sharing? Linking in the code below tries to open the file but it closes immediately without any notification, but my app is still working fine. Is there some special way to build URLs for deep linking for a specific file type? Any ideas for the best solution?
I see that there is old package react-native-file-opener but it's no longer maintained. This solution would be great.
Simplified code for download component:
import React, { Component } from 'react';
import { Text, View, Linking, TouchableOpacity } from 'react-native';
import { Icon } from 'react-native-elements';
import RNFS from 'react-native-fs';
import { showToast } from '../../services/toasts';
class DownloadFile extends Component {
state = {
isDone: false,
};
handleDeepLinkPress = (url) => {
Linking.openURL(url).catch(() => {
showToast('defaultError');
});
};
handleDownloadFile = () => {
RNFS.downloadFile({
fromUrl: 'https://www.toyota.com/content/ebrochure/2018/avalon_ebrochure.pdf',
toFile: `${RNFS.DocumentDirectoryPath}/car.pdf`,
}).promise.then(() => {
this.setState({ isDone: true });
});
};
render() {
const preview = this.state.isDone
? (<View>
<Icon
raised
name="file-image-o"
type="font-awesome"
color="#f50"
onPress={() => this.handleDeepLinkPress(`file://${RNFS.DocumentDirectoryPath}/car.pdf`)}
/>
<Text>{`file://${RNFS.DocumentDirectoryPath}/car.pdf`}</Text>
</View>)
: null;
return (
<View>
<TouchableOpacity onPress={this.handleDownloadFile}>
<Text>Download File</Text>
</TouchableOpacity>
{preview}
</View>
);
}
}
export default DownloadFile;
After some research, I decided to use react-native-fetch-blob. From version 0.9.0 it's possible to open downloaded file with Intent and use Download Manager. It also has API for iOS for opening documents.
Code now:
...
const dirs = RNFetchBlob.fs.dirs;
const android = RNFetchBlob.android;
...
handleDownload = () => {
RNFetchBlob.config({
addAndroidDownloads: {
title: 'CatHat1.jpg',
useDownloadManager: true,
mediaScannable: true,
notification: true,
description: 'File downloaded by download manager.',
path: `${dirs.DownloadDir}/CatHat1.jpg`,
},
})
.fetch('GET', 'http://www.swapmeetdave.com/Humor/Cats/CatHat1.jpg')
.then((res) => {
this.setState({ path: res.path() });
})
.catch((err) => console.log(err));
};
...
render() {
...
<Icon
raised
name="file-pdf-o"
type="font-awesome"
color="#f50"
onPress={() => android.actionViewIntent(this.state.path, 'image/jpg')}
...
}
I want to take an image using react-native image picker,
I am using npm run android command but as the application runs in expo it shows this error:
undefined is not an object(evaluating 'imagepickerManager.showimagepicker')
As I am using expo project index.android.js is not present in the project so react-native run-android command is not working.
Can someone please guide me how to recover this error?
import React, {Component} from 'react';
import {Text, View, TouchableOpacity, Image} from 'react-native';
// var ImagePicker = require('react-native-image-picker');
import * as ImagePicker from 'react-native-image-picker';
// More info on all the options is below in the README...just some common use cases shown here
var options = {
title: 'Select Avatar',
customButtons: [
{name: 'fb', title: 'Choose Photo from Facebook :'},
],
storageOptions: {
skipBackup: true,
path: 'images'
}
};
export default class App extends Component{
constructor(props){
super(props);
this.state={
avatarSource:null
}
}
render(){
let img=this.state.avatarSource == null?null:
<Image
source={this.state.avatarSource}
style={{height:200, width:300}}
/>
return(
<View>
<Text>Welcome to Image Picker</Text>
<TouchableOpacity onPress = {this.show.bind()} >
<Text>Load Images</Text>
</TouchableOpacity>
{img}
</View>
)
}
show(){
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button please: ', response.customButton);
}
else {
let source = { uri: response.uri };
// You can also display the image using data:
// let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source
});
}
});
}
}
I was having the same issue. And solved it in following way -
react-native link react-native-image-picker
run the react-native-run-ios and react-native run-android command
More description here
I just fix this error by running react-native link then rebuild your app. It should work as expected. :)
import * as ImagePicker from "react-native-image-picker"