Is there a way to connect to localhost from Android? - android

I am creating an application in React Native with Expo and I am using USB debugging mode to see the view of this application.
The problem is that I am consuming an API, which is found locally on my computer.
When I run the program with Expo from USB debugging mode I can't connect to localhost, but when I run the application with Expo web mode I can connect and consume the API.
Obviously I tried localhost and 127.0.0.1 but neither one worked for me.
For what it's worth:
This would be my code:
import { StatusBar } from 'expo-status-bar';
import React, { Component, useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, ActivityIndicator, Image } from 'react-native';
const API_ENDPOINT = "https://127.0.0.1:5001/api/Medicines/";
export default function App () {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
setIsLoading(true);
fetch(API_ENDPOINT)
.then(response => response.json())
.then(results => {
setData(results);
setIsLoading(false);
})
.catch(err => {
setIsLoading(false);
setError(err);
});
}, []);
if (isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" color="#5500dc" />
</View>
);
}
if (error) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 18}}>
Error fetching data... Check your network connection!
</Text>
</View>
);
}
return (
<View style={styles.container}>
<Text>Successful connection</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
I run the program in the cmd with the command expo start --localhost --android to start the USB debugging mode and see the application from the Expo mobile application, and this is what appears to me:
And this is the same application but from the Expo web option:

Full answer is here.
in short:
adb devices //gives your device(s) name
adb -s <device name> reverse tcp:5001 tcp:5001

Related

How can I add a background image to my react native app?

I am fairly new to react native, but I have some experience. I am creating my own app for both ios and android by following along a tutorial that I had already completed and making my own modifications. As I was in the middle of creating an app, I forgot to add a background image. After struggling with this for several days, I'm desperate, so I decided to ask my question on here.
I am trying to add the background image to my App.js file. The image loads properly, but my page content ( which is inside <LifelineNavigator />) is either hidden or has disappeared for android. And for ios, the content seems to be in a small centered flexbox. Also, I am trying to remove the white background.
Any suggestions would definitely help. Thanks so much! God bless!
Here is my code:
import React, { useState } from "react";
import { StyleSheet, View, ImageBackground } from "react-native";
import * as Font from "expo-font";
import AppLoading from "expo-app-loading";
import { enableScreens } from "react-native-screens";
import LifelineNavigator from "./src/navigation/LifelineNavigator";
enableScreens();
const fetchFonts = () => {
return Font.loadAsync({
"Gotham-Medium": require("./src/assets/fonts/Gotham-Font/Gotham-Medium.otf")
const image = {
uri: "https://i.ibb.co/8z6QbTS/Lifeline-Gradient-Background-24.png",
};
const App = () => {
const [fontLoaded, setFontLoaded] = useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={() => setFontLoaded(true)}
onError={(err) => console.log(err)}
/>
);
}
return (
<View >
<ImageBackground source={image} style={styles.image}>
<View style={ styles.container }>
<LifelineNavigator />
</View>
</ImageBackground>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
// backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
image: {
width: "100%",
height: "100%" ,
}
});
export default App;
IOS Screenshot
Android Screenshot
import React from "react";
import { ImageBackground, StyleSheet, Text, View } from "react-native";
const image = { uri: "https://reactjs.org/logo-og.png" };
const App = () => (
<View style={styles.container}>
<ImageBackground source={image} resizeMode="cover" style={styles.image}>
<Text style={styles.text}>Inside</Text>
</ImageBackground>
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
},
image: {
flex: 1,
justifyContent: "center"
},
text: {
color: "white",
fontSize: 42,
lineHeight: 84,
fontWeight: "bold",
textAlign: "center",
backgroundColor: "#000000c0"
}
});
export default App;
follow this documentation > https://reactnative.dev/docs/imagebackground
it may solve your problem

React Native: Firebase OTP issues in android device

I have implemented the functionality of firebase OTP, for authentication of the user to my App.
When I created the build, The OTP functionality is working fine with IOS but not with android, in android the OTP expires soon.
Here is the case:
Case 1
Android Device A
App installed in device A, and register with the mobile number of Device A (the same device),
I got the OTP but when I entered it shows me an invalid OTP due to the OTP had been expired already
Case 2
Android Device A, and Android Device B
App installed in device A, and registered with the mobile number of Device B,
I got the OTP on Device B and I entered it in device A where the app is installed, It was working fine.
Here is my code and configuration
import React, { Fragment, Component } from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
TextInput,
Button,
Animated,
} from 'react-native';
import auth from '#react-native-firebase/auth';
import { COLORS } from './App/Auth/Colors';
import { STRINGS } from './App/Resource/Strings';
import { Animation_Open, Animation_Close } from './App/Auth/Functions';
export default class Demo extends Component {
constructor(props) {
super(props);
this.animatedValue = new Animated.Value(-500);
this.state = {
phone: '+91',
code: '',
confirm: null,
};
}
componentDidMount() {
console.log('componentDidMount Demo');
}
OnPressContinue = async () => {
auth()
.signInWithPhoneNumber(this.state.phone)
.then(confirmResult => {
console.log('confirmResult', confirmResult);
this.setState({ confirm: confirmResult });
})
.catch(error => {
console.log('My Error', error);
});
}
OnPressCodeSent = async () => {
try {
var a = await this.state.confirm.confirm(this.state.code);
console.log('a', a);
} catch (error) {
console.log('Invalid code.', error);
}
}
render() {
return (
<SafeAreaView style={styles.container}>
<StatusBar />
<View>
<View>
<TextInput
placeholder="Enter A Number"
value={this.state.phone}
onChangeText={(text) => this.setState({ phone: text })}
keyboardType="numeric"
style={{ padding: 10, borderBottomWidth: 1, width: '100%', color: 'black' }}
/>
<View style={{ marginTop: 20 }}>
<Button
title="Continue"
onPress={() => this.OnPressContinue()} />
</View>
</View>
<View style={{ marginTop: 20 }}>
<TextInput
placeholder="Enter Code"
value={this.state.code}
onChangeText={(text) => this.setState({ code: text })}
style={{ padding: 10, borderBottomWidth: 1, width: '100%', color: 'black' }}
/>
<View style={{ marginTop: 20 }}>
<Button
title="Send"
onPress={() => this.OnPressCodeSent()} />
</View>
</View>
</View>
{/* //! Toster */}
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
The issue has been resolved:
If the OTP will receive in the same device we will auto add, and compare.

my app js not working in react native. what my mistake?

I newbie for react native. when I learning to hello world in app.js. when I run for android "native-react run-android" build success but not working on my phone. not change
this is my code in app.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Hello, Steven Wiaji, S.Kom</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text style={styles.instructions}>{instructions}</Text>
</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,
},
});
this is adb running
this is when i run on my phone
There's nothing wrong with the code. Probably issue with node_modules. You might wanna delete the folder and do a npm i or yarn again.
Here's a working example.
https://snack.expo.io/S1oozjjUV

open a server in react native

I want to display (android/ios) 360 tour with react-vr but for doing that I need to open the tour in a WebView component using server request url, but all the packages that I have found do not work or return the same bug:
react-native-static-server
react-native-http-bridge
here you can find my problem with react-native-static-server
so even if I follow the tutorial and I respect all the rules the local server does not work and shows me this bug.
This is the code off app.js:
import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; import StaticServer from 'react-native-static-server'; let server = new StaticServer(8080); // Start the server server.start().then((url) => { console.log("Serving at URL", url); }); server.stop(); type Props = {}; export default class App extends Component<Props> { render() { return ( <View style={styles.container}> <Text style={styles.welcome}>Welcome to React Native!</Text> <Text style={styles.instructions}>To get started, edit App.js</Text> </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, }, });
Someone can suggest a way to implement the server in my react-native app or a tutorial to solve this problem thanks

How to access the camera - React Native

This should be included in the react-native APIs but I cannot seem to find any API included out of the box.
I want to open up the camera on the click of a button. I can see some APIs just for iOS but react-native should make things cross-platform.
Does anyone know how to access the camera (not the gallery) using react-native?
You might like to use react-native-camera module for this.
Here's an example usage of the library:
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
class BadInstagramCloneApp extends Component {
render() {
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>
</View>
);
}
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => console.log(data))
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
AppRegistry.registerComponent('BadInstagramCloneApp', () => BadInstagramCloneApp);
Currently react-native-camera is deprecated and if you want to achieve native performance and reach feature support good choice is https://github.com/mrousavy/react-native-vision-camera
Features:
Photo, Video and Snapshot capture
Customizable devices and multi-cameras (smoothly zoom out to "fish-eye" camera)
Customizable FPS
Frame Processors (JS worklets to run QR-Code scanning, facial recognition, AI object detection, realtime video chats, ...)
Smooth zooming (Reanimated)
Fast pause and resume
HDR & Night modes
Example:
function App() {
const devices = useCameraDevices('wide-angle-camera')
const device = devices.back
if (device == null) return <LoadingView />
return (
<Camera
style={StyleSheet.absoluteFill}
device={device}
isActive={true}
/>
)
}
Documentation:
https://mrousavy.com/react-native-vision-camera/docs/guides
In React Native you can access the camera by first installing it using NPM:
npm install react-native-camera --save
react-native link react-native-camera
Then use this in your Component:
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => console.log(data))
.catch(err => console.error(err));
}
See this github repo for full example:
https://github.com/lwansbrough/react-native-camera
I found react-native-picker image picker handier for my needs, it can be useable for both camera and gallery. for the bellow example you need to install version: "react-native-image-picker": "^3.3.2",
https://www.npmjs.com/package/react-native-image-picker
import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, Image} from 'react-native';
import cameraImage from '../../../../assets/icons/camera.png';
import galleryImage from '../../../../assets/icons//gallery.png';
import {TouchableWithoutFeedback} from 'react-native-gesture-handler';
import * as ImagePicker from 'react-native-image-picker';
import {PermissionsAndroid} from 'react-native';
const ImagePicker = () => {
const [responseCamera, setResponseCamera] = React.useState(null);
const [responseGallery, setResponseGallery] = React.useState(null);
const openCameraWithPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'App Camera Permission',
message: 'App needs access to your camera ',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
ImagePicker.launchCamera(
{
mediaType: 'photo',
includeBase64: false,
maxHeight: 200,
maxWidth: 200,
},
(response) => {
console.log(response);
setResponseCamera(response);
setResponseGallery(null);
},
);
} else {
console.log('Camera permission denied');
}
} catch (err) {
console.warn(err);
}
};
return (
<View
style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
margin: 4,
}}>
<TouchableOpacity onPress={() => openCameraWithPermission()}>
{responseCamera === null ? (
<Image style={styles.icon} source={cameraImage} />
) : (
<Image style={styles.icon} source={{uri: responseCamera.uri}} />
)}
</TouchableOpacity>
<TouchableOpacity
onPress={() =>
ImagePicker.launchImageLibrary(
{
mediaType: 'photo',
includeBase64: false,
maxHeight: 200,
maxWidth: 200,
},
(response) => {
setResponseGallery(response);
setResponseCamera(null);
},
)
}>
{responseGallery === null ? (
<Image style={styles.icon} source={galleryImage} />
) : (
<Image style={styles.icon} source={{uri: responseGallery.uri}} />
)}
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
icon: {
height: 50,
width: 50,
},
});
export default ImagePicker;
permissions for android:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />

Categories

Resources