Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all 29627 articles
Browse latest View live

Need to hide and disable status bar in react native using android native code

$
0
0

I am trying to disable status bar and home and history buttom in react native using android native code. React native provide function for back btn so did that.

MainActivity.java

package com.kiosk;import com.facebook.react.ReactActivity;import com.facebook.react.ReactActivityDelegate;import com.facebook.react.ReactRootView;import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;import org.devio.rn.splashscreen.SplashScreen;import android.os.Bundle;public class MainActivity extends ReactActivity {  /**   * Returns the name of the main component registered from JavaScript. This is used to schedule   * rendering of the component.   */   @Override    protected void onCreate(Bundle savedInstanceState) {        SplashScreen.show(this);        FullScreencall();        super.onCreate(savedInstanceState);    }    public void FullScreencall() {    if(Build.VERSION.SDK_INT < 19){         View v = this.getWindow().getDecorView();        v.setSystemUiVisibility(View.GONE);    } else {            //for higher api versions.            View decorView = getWindow().getDecorView();         int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;        decorView.setSystemUiVisibility(uiOptions);    }}  @Override  protected String getMainComponentName() {    return "AwesomeProject";  }  @Overrideprotected ReactActivityDelegate createReactActivityDelegate() {return new ReactActivityDelegate(this, getMainComponentName()) {@Overrideprotected ReactRootView createRootView() {return new RNGestureHandlerEnabledRootView(MainActivity.this);}};}}

ERRORS getting :

error: cannot find symbol         v.setSystemUiVisibility(View.GONE);                                ^  symbol:   variable View  location: class MainActivityerror: cannot find symbol         View decorView = getWindow().getDecorView();        ^  symbol:   class View  location: class MainActivity error: cannot find symbol         int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;                        ^  symbol:   variable View  location: class MainActivityerror: cannot find symbol         int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;                                                              ^         symbol:   variable View  location: class MainActivity

Have you ever done that in react native or java please help me I stuck, some code snippets will be helpful


React-Native alternative to AlertIOS.prompt for android?

$
0
0

I am following a tutorial for react-native, however they are doing it for IOS, there is one part where they use AlertIOS.prompt like this

AlertIOS.prompt('Add New Item',  null,  [    {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},    {      text: 'Add',      onPress: (text) => {        this.itemsRef.push({ title: text })      }    },  ],'plain-text');

I am trying to remake this for android but cannot get it working, I did find this https://www.npmjs.com/package/react-native-prompt

import Prompt from 'react-native-prompt';<Prompttitle="Say something"placeholder="Start typing"defaultValue="Hello"visible={ this.state.promptVisible }onCancel={ () => this.setState({  promptVisible: false,  message: "You cancelled"}) }onSubmit={ (value) => this.setState({  promptVisible: false,  message: `You said "${value}"`}) }/>

However I cannot get this to work either, It is supposed to display the prompt when I press a button but nothing happens..

Here is the full original code with AlertIOS

'use strict';import React, {Component} from 'react';import ReactNative from 'react-native';const firebase = require('firebase');const StatusBar = require('./components/StatusBar');const ActionButton = require('./components/ActionButton');const ListItem = require('./components/ListItem');const styles = require('./styles.js')const {  AppRegistry,  ListView,  StyleSheet,  Text,  View,  TouchableHighlight,  AlertIOS,} = ReactNative;// Initialize Firebaseconst firebaseConfig = {  apiKey: "AIzaSyA9y6Kv10CAl-QOnSkMehOyCUejwvKZ91E",  authDomain: "dontforget.firebaseapp.com",  databaseURL: "https://dontforget-bd066.firebaseio.com",  storageBucket: "dontforget-bd066.appspot.com",};const firebaseApp = firebase.initializeApp(firebaseConfig);class dontforget extends Component {  constructor(props) {    super(props);    this.state = {      dataSource: new ListView.DataSource({        rowHasChanged: (row1, row2) => row1 !== row2,      })    };    this.itemsRef = this.getRef().child('items');  }  getRef() {    return firebaseApp.database().ref();  }  listenForItems(itemsRef) {    itemsRef.on('value', (snap) => {      // get children as an array      var items = [];      snap.forEach((child) => {        items.push({          title: child.val().title,          _key: child.key        });      });      this.setState({        dataSource: this.state.dataSource.cloneWithRows(items)      });    });  }  componentDidMount() {    this.listenForItems(this.itemsRef);  }  render() {    return (<View style={styles.container}><StatusBar title="Grocery List" /><ListView          dataSource={this.state.dataSource}          renderRow={this._renderItem.bind(this)}          enableEmptySections={true}          style={styles.listview}/><ActionButton onPress={this._addItem.bind(this)} title="Add" /></View>    )  }  _addItem() {    AlertIOS.prompt('Add New Item',      null,      [        {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},        {          text: 'Add',          onPress: (text) => {            this.itemsRef.push({ title: text })          }        },      ],'plain-text'    );  }  _renderItem(item) {    const onPress = () => {      AlertIOS.alert('Complete',        null,        [          {text: 'Complete', onPress: (text) => this.itemsRef.child(item._key).remove()},          {text: 'Cancel', onPress: (text) => console.log('Cancelled')}        ]      );    };    return (<ListItem item={item} onPress={onPress} />    );  }}AppRegistry.registerComponent('dontforget', () => dontforget);

Could anyone tell me how I could make this work for android?

Expo Andriod deployment issue

$
0
0

Expo CLI 4.0.13 environment info:

System:OS: Windows 10 10.0.18363

Binaries:Node: 12.18.3 - C:\Program Files\nodejs\node.EXEnpm: 6.14.6 - C:\Program Files\nodejs\npm.CMD

IDEs:Android Studio: Version 4.0.0.0 AI-193.6911.18.40.6626763

npmPackages:expo: ^38.0.0 => 38.0.10

react: 16.11.0 => 16.11.0

react-dom: 16.11.0 => 16.11.0react-native: https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz => 0.62.2react-native-web: ~0.11.7 => 0.11.7Expo Workflow: managed

When I am running - expo build:android -cIt works well till Key aliasafter I provide the value it does not go the next step. It is stuck at

? Key alias » xxxxxxxx

If I click enter again it takes the alias value as null and throws the following error

"keystore.keyAlias" is not allowed to be empty.

This is definitely my system issue, when I tried doing it from a friends machine it worked well but I want to be able to do it from my system this time. There is no issues with the project.

Stuck on deployment for the past two day, Please Let me know if you need anymore info

I would really appreciate any help.

Change TextInput Style on Focus React Native Paper

$
0
0

First of all, I've researched through other posts and find many solutions but nothing work in React Native Paper ?

I need change TextInput Style on Focus in React Native Paper

React Native Socket.io client not working after ejecting expo

$
0
0

Earlier in expo app Socket io client was working fine. But when I ejected expo and converted the app into bare react-native cli socket io is not working. It gives the following error:

"[TypeError: undefined is not an object (evaluating 'packet.data.sid')]"

Client code:

import SocketIO from "socket.io-client";const connectionConfig = {  transports: ["websocket"]};constructor() {    super();    this.socket = SocketIO(socketUrl, connectionConfig);    this.socket.on("connect", () => {      console.log("connected to socket server 3001");    });}

I already tried adding android:usesCleartextTraffic="true" in Manifest file and added this in network config file

<base-config cleartextTrafficPermitted="true"><trust-anchors><certificates src="system" /></trust-anchors></base-config>

and this

<domain-config cleartextTrafficPermitted="true"><domain includeSubdomains="true">domain</domain></domain-config>

Don't show admob ads in my react native apps.. Please help me my programmers brothers

$
0
0

I'm try to add admob ads in my react native app. That not show any ads in my app

React Native APK installing and App Crashing problem

$
0
0

I'm using Samsung Galaxy J7 2017. When I try to install my React Native app, I get this error: "APK not installed" and when I try to install in Samsung J2, I can. But When I open the app, the app crashes.

React Native not loading image from sdcard in android

$
0
0

I am trying to load image from external sdcard after I take photo from camera in React native image component as following, but it is not rendering in android. I even checked if there is image missing at that location, but that's not the problem. But it works well in case of iOS to load image from location after taking photo from camera.

<Image source={{uri:'/storage/emulated/0/Pictures/image-0ea0d714-9469-432b-8869-b6637be2be10.jpg'}} style={{height:200, width:200}} />

Here's my permission list in AndroidManifest.xml

<!-- For Image picker start --><uses-permission android:name="android.permission.CAMERA" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-feature android:name="android.hardware.camera" android:required="false"/><uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>

Load image from phone local storage of android react-native + expo

$
0
0

My code does not gives any error when executed over expo (react-native) but the image is also not loading. The path I get from details of the image in android is "Internal storage/DCIM/images.jpeg" therefore searching over forums read a suggestion to replace Internal storage with "file:///storage/emulated/0/". But this too does not work. The only output I get is the Hello, world! text.My device is Huawei BG2-U01.

Hope I am not missing out on any basics.

import React, { Component } from 'react';import { Text, View,Image } from 'react-native';export default class HelloWorldApp extends Component {  render() {    return (<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}><Text>Hello, world!</Text><Image source={{uri:'file:///storage/emulated/0/DCIM/images.jpeg'}} style={{width: 60, height: 60}} /> </View>    );  }}

Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation

$
0
0
FAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':react-native-linear-gradient:compileDebugJavaWithJavac'.> Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation.

When I upgraded to Mac os Big sur and run,

npx react-native run-android

I got this error (Android). I have tried a lot of solutions from Stack Overflow, but none of them worked.

I have created a fresh project and it's working. Also some of the old projects are also working perfectly.

*react-native Version: "0.63.3",*

Please help me to find a solution?

React Native: Stop Automatic Navigation/Screen Focus after Flatlist Re-rendering

$
0
0

I have a Screen with a Flatlist and after navigating to other screens, the screen with the flatlist shows up again after re-rendering.I have removed any navigation attached to the flat list by commenting out the onpress as shown

renderRow = ({item}) => {          var lt = parseFloat(this.state.lat)          var lg = parseFloat(this.state.longy)        return (<View><TouchableOpacity             // onPress={()=>this.props.navigation.navigate('chatpage',item)}            style={{padding:10,borderBottomColor:'#ccc',borderBottomWidth:1}}><Text style={{fontSize:10}}>{item.name} is {getDistance(                 { latitude: lt, longitude: lg },                { latitude: item.latitude, longitude: item.longitude }                )} meters away</Text></TouchableOpacity></View>               )    }

The flatlist is shown below

<FlatList                               data={users.sort((a, b) => (                  getDistance({ latitude: lt, longitude: lg }, { latitude: a.latitude,                    longitude: a.longitude }) - getDistance({ latitude: lt, longitude: lg },                { latitude: b.latitude, longitude: b.longitude })               ))}                renderItem = {this.renderRow}                keyExtractor={(item) => item.phone}   />  

How can I stay on a given page without automatically redirecting to the screen with the FLatlist.

How to work with Siri and Google Assitant in React Native

$
0
0

I am trying to work with Siri and Google Assistant in my React Native project. I want to add my custom speeches to my project and when they are called through Siri or Google Assistant when app is in background or foreground mode, a custom function inside the app be called.Is there any package or a code that can help me?

height vs position vs padding in KeyboardAvoidingView "behavior"

$
0
0

There is a "behavior" property in KeyboardAvoidingView, e.g.:

import { KeyboardAvoidingView } from 'react-native';<KeyboardAvoidingView style={styles.container} behavior="padding" enabled>    ... your UI ...</KeyboardAvoidingView>

It can be picked as one of three choices: 'height', 'position', or 'padding'. The difference is not explained in the documentation. All it says is that it's not required to set the property, and has a note:

Note: Android and iOS both interact with this prop differently. Android may behave better when given no behavior prop at all, whereas iOS is the opposite.

What effect are these settings supposed to have?

npx react-native run-android does not work - "java.io.IOException: The filename, directory name, or volume label syntax is incorrect"

$
0
0

Just recently ejected expo and I'm trying to run my app on an android device. I followed the instructions (hopefuly right) but I keep getting this error when I try to run my app:

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.Use '--warning-mode all' to show the individual deprecation warnings.See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warningsFAILURE: Build failed with an exception.* What went wrong:A problem occurred configuring project ':app'.> java.io.IOException: The filename, directory name, or volume label syntax is incorrect* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.* Get more help at https://help.gradle.orgBUILD FAILED in 3serror Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081FAILURE: Build failed with an exception.* What went wrong:A problem occurred configuring project ':app'.> java.io.IOException: The filename, directory name, or volume label syntax is incorrect* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.* Get more help at https://help.gradle.orgBUILD FAILED in 3s    at makeError (C:\Users\User\Documents\jad for eject\jad\jad\node_modules\execa\index.js:174:9)    at C:\Users\User\Documents\jad for eject\jad\jad\node_modules\execa\index.js:278:16    at processTicksAndRejections (internal/process/task_queues.js:97:5)    at async runOnAllDevices (C:\Users\User\Documents\jad for eject\jad\jad\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:5)    at async Command.handleAction (C:\Users\User\Documents\jad for eject\jad\jad\node_modules\@react-native-community\cli\build\index.js:186:9)

Thanks for the help!

Task :unimodules-react-native-adapter:compileReleaseKotlin FAILED

$
0
0

When i try to convert react native app to apk, I can create output folder but then I get this error:

Task :unimodules-react-native-adapter:compileReleaseKotlin FAILED

FAILURE: Build failed with an exception.

  • What went wrong:Execution failed for task ':unimodules-react-native-adapter:compileReleaseKotlin'.

Could not resolve all artifacts for configuration ':unimodules-react-native-adapter:releaseCompileClasspath'.Could not download nativeloader-0.8.0.jar (com.facebook.soloader:nativeloader:0.8.0)> Could not get resource 'https://jcenter.bintray.com/com/facebook/soloader/nativeloader/0.8.0/nativeloader-0.8.0.jar'.> Could not GET 'https://jcenter.bintray.com/com/facebook/soloader/nativeloader/0.8.0/nativeloader-0.8.0.jar'.> jcenter.bintray.comCould not download okhttp-urlconnection-3.12.1.jar (com.squareup.okhttp3:okhttp-urlconnection:3.12.1)> Could not get resource 'https://jcenter.bintray.com/com/squareup/okhttp3/okhttp-urlconnection/3.12.1/okhttp-urlconnection-3.12.1.jar'.> Could not GET 'https://jcenter.bintray.com/com/squareup/okhttp3/okhttp-urlconnection/3.12.1/okhttp-urlconnection-3.12.1.jar'.> jcenter.bintray.comCould not download okhttp-3.12.1.jar (com.squareup.okhttp3:okhttp:3.12.1)> Could not get resource 'https://jcenter.bintray.com/com/squareup/okhttp3/okhttp/3.12.1/okhttp-3.12.1.jar'.> Could not GET 'https://jcenter.bintray.com/com/squareup/okhttp3/okhttp/3.12.1/okhttp-3.12.1.jar'.> jcenter.bintray.com


ReferenceError: Can't find variable: colors [closed]

$
0
0

[It did not specify where the error lay.]

How to use expo-camera

$
0
0

I'm trying to install expo-camera but i'm getting this error.

Installing 1 SDK 40.0.0 compatible native module using npm.

npm installnpm ERR! code ERESOLVEnpm ERR! ERESOLVE unable to resolve dependency treenpm ERR!npm ERR! Found: @unimodules/core@6.0.0npm ERR! node_modules/@unimodules/corenpm ERR! @unimodules/core@"~6.0.0" from expo@40.0.0npm ERR! node_modules/exponpm ERR! expo@"~40.0.0" from the root projectnpm ERR! peer @unimodules/core@"*" from expo-application@2.4.1npm ERR! node_modules/expo-applicationnpm ERR! expo-application@"~2.4.1" from expo@40.0.0npm ERR! node_modules/exponpm ERR! expo@"~40.0.0" from the root projectnpm ERR! 1 more (expo-location)npm ERR!npm ERR! Could not resolve dependency:npm ERR! peer @unimodules/core@"~5.1.2" from expo-camera@9.1.0npm ERR! node_modules/expo-cameranpm ERR! expo-camera@"~9.1.0" from the root projectnpm ERR!npm ERR! Fix the upstream dependency conflict, or retrynpm ERR! this command with --force, or --legacy-peer-depsnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.npm ERR!npm ERR! See /home/muaz/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:npm ERR! /home/muaz/.npm/_logs/2020-12-12T16_45_39_635Z-debug.log

npm exited with non-zero code: 1Error: npm exited with non-zero code: 1at ChildProcess.completionListener (/usr/lib/node_modules/expo-cli/node_modules/@expo/spawn-async/src/spawnAsync.ts:65:13)at Object.onceWrapper (node:events:483:26)at ChildProcess.emit (node:events:376:20)at maybeClose (node:internal/child_process:1055:16)at Process.ChildProcess._handle.onexit (node:internal/child_process:288:5)...at Object.spawnAsync [as default] (/usr/lib/node_modules/expo-cli/node_modules/@expo/spawn-async/src/spawnAsync.ts:26:19)at NpmPackageManager._runAsync (/usr/lib/node_modules/expo-cli/node_modules/@expo/package-manager/src/NodePackageManagers.ts:157:31)at NpmPackageManager.addAsync (/usr/lib/node_modules/expo-cli/node_modules/@expo/package-manager/src/NodePackageManagers.ts:100:18)at installAsync (/usr/lib/node_modules/expo-cli/src/commands/install.ts:129:3)at Command. (/usr/lib/node_modules/expo-cli/src/exp.ts:346:7)

Minimizing the react native app without going back

$
0
0

I navigate normally from screen A to screen B

I want to make screen B as the root of the app / the navigation should ignore screen A and deal with screen B as the root

so in screen B , when the user hit the android navigation back , it should minimize the appnot to return to screen A

here's my code in screen B

BackHandler.addEventListener("hardwareBackPress" , () => {  BackHandler.exitApp();});

when I hit the android back button

the actual result

it minimize the app and when I open it again , it shows screen A

the expected result

it should only minimize the app and when I open it again , it shows the same screen B

By the way , it there any method to make a screen as a root instead of putting these many listeners manually and making the things complicated?

In more correct meaning , To change the root screen programmatically , as React Navigation only initialize it and cannot change it later

example

const RootNavigator = createSwitchNavigator(  {     ScreenA : ScreenA,     ScreenB : ScreenB  },  {    initialRouteName: 'ScreenA' // I mean here  });

What if I want to change this initialRouteName in run-time after the ReactNavigation initialization

React Native Custom Text Selection Menu

$
0
0

We are making a reading book application with React Native, but we have a problem about context menu. As you know many reading applications have a customized menu when user long press on text. There is a different menu instead of standart Android context menu (Copy-Paste-Select All)

For example: https://prnt.sc/w14pap (App XODO - https://play.google.com/store/apps/details?id=com.xodo.pdf.reader&hl=tr)enter image description here

We want to show a menu like that.

We tried both in javascript side and react native plugin (https://github.com/Astrocoders/react-native-selectable-text), but we couldn't succeed.

Plugin supports only text, but we want to show icons only.

Could you help me please how can I make a context menu like this?

What we need?

  • When user long press on text, a customized menu must be shown
  • When user extend selection, the customized menu mustn't be lost or should be shown again.
  • When user long press or extend selection, we must get start and end indexes of selection.
  • We are using Text component because of we can colorize/underline some words of text. (TextInput doesn't support partial styling)

If it is not possible to do it without native bridge, is there any ready plugins in native side to bridge?

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. React-Native

$
0
0

So I have been doing a lot of research as to why this isn't working and wasn't able to find anything.Does anyone know what this error pertains too?

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.    Check the render method of `App`.    This error is located at:        in App (created by ExpoRoot)        in ExpoRoot        in RCTView (created by View)        in View (created by AppContainer)        in RCTView (created by View)        in View (created by AppContainer)        in AppContainer    - node_modules\expo\build\logs\LogSerialization.js:160:14 in _captureConsoleStackTrace    - node_modules\expo\build\logs\LogSerialization.js:41:26 in serializeLogDataAsync    - ... 9 more stack frames from framework internals

Here is my App.js:

import * as Icon from '@expo/vector-icons'import * as AppLoading  from 'expo-app-loading'import {Asset} from 'expo-asset'import * as Font from 'expo-font'import React from 'react'import { StatusBar, StyleSheet, View } from 'react-native'import AppNavigator from './navigation/AppNavigator'export default class App extends React.Component {  state = {    isLoadingComplete: false,  }  render() {    if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {      return (<AppLoading          startAsync={this._loadResourcesAsync}          onError={this._handleLoadingError}          onFinish={this._handleFinishLoading}        />      )    } else {      return (<View style={styles.container}><StatusBar hidden /><AppNavigator /></View>      )    }  }  _loadResourcesAsync = async () => {    return Promise.all([      Asset.loadAsync([        require('./assets/images/splash.png'),        require('./assets/images/icon.png'),      ]),      Font.loadAsync({        //This is the font that we are using for our tab bar        ...Icon.MaterialIcons.font,        ...Icon.MaterialCommunityIcons.font,        ...Icon.FontAwesome.font,        ...Icon.Feather.font,      }),    ])  }  _handleLoadingError = error => {    // In this case, you might want to report the error to your error    // reporting service, for example Sentry    console.warn(error)  }  _handleFinishLoading = () => {    this.setState({ isLoadingComplete: true })  }}const styles = StyleSheet.create({  container: {    flex: 1,    backgroundColor: '#fff',  },})

I have installed all the necessary modules, reset the cache, checked the import statements, but nothing seems to work. Any help would be appreciated!

Viewing all 29627 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>