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

how to use print attribute react-native-share

$
0
0

I am using the react-native-share extension for the share and print Pdf document. I am trying to add The 'Print' attribute but it is not working or I couldn't get it rightI follow this document https://react-native-community.github.io/react-native-share/docs/share-open#activitytype

and i used the example here https://react-native-community.github.io/react-native-share/docs/share-open#activityitemsources-ios-onlyAccording to this document, I created an object like

const url = this.props.navigation.state.params.document.url           {            item:{            print : url            }          },

enter image description here


Expo run on android emulator using windows 10

$
0
0

Can I run android emulator without an android phone? I have installed android studio and I've already installed android virtual device. However, when I try to run it, it gives an error like this :

Couldn't start project on Android: Error running adb: No Android device found. Please connect a device and follow the instructions here to enable USB debugging:https://developer.android.com/studio/run/device.html#developer-device-options. If you are using Genymotion go to Settings -> ADB, select "Use custom Android SDK tools", and point it at your Android SDK directory.

I just want to see the emulator in my pc without usb. I have an iPhone but it just shows up in my phone not in my pc using expo scan barcode. I don't want to do that because in my opinion it's not comfortable for debugging etc. I am using windows in my pc so I can't use iOS for emulator.

how to run expo android emulator on windows?

External keyboard event handlers stop responding

$
0
0

I've been working on a project which needs to capture keystrokes from an external keyboard (a handheld barcode scanner really) anywhere in the app. Using react-native, this should be trivial, especially with the library react-native-keyevent.

Works perfectly on the initial load. I then navigate to another part of the app (using react-navigation) and try to scan a barcode; nothing happens. I replaced the react-native-keyevent overrides MainActivity.java with some simple Log.d("KeyEvents", "..."), overriding dispatchKeyEvent, onKeyUp, onKeyMultiple and onKeyDown. I only log, then call super.

Same behaviour. Logs fine until I navigate, then it stops. After investigating the Android docs, it seems Views can override key handlers, and thereby 'steal' keystrokes. However I'm stuck finding out which view steals the focus. Also there's really no keyboard handling in react-native by default, so to my understanding, everything should be passed on to the activity.

Wandering hopelessly around in the react-native codebase, I stumbled upon TVEventHandler which I use to log if a view requests focus:

import TVEventHandler from 'react-native/Libraries/Components/AppleTV/TVEventHandler';(new TVEventHandler).enable('foo', function(){    console.log(arguments);})

Right before the handlers stop working, this line indeed logs some focus events with a view tag. However, I don't know how to find out which view has a certain tag.

Can someone point me in the right direction where to look?

How to receive image file path shared from gallery to react native app

$
0
0

My goal is to open an Image Upload screen of my react native app and fetch that shared image file path (like as file://). I want to receive the image file path shared from the gallery to react native app. I am beginner to this and I have searched on google and stack Overflow and found this to add in MainActivity.java file, although I am receiving the image as content://com.android.providers.downloads.documents/document/38 but I don't know how to convert this filePath to file path like file:///storage/emulated/0/Android/data/com.newProject/files/Pictures/ff345380-4bbd-4153-8a8b-c6f98ae62627.jpg.MainActivity.java file

@Overrideprotected ReactActivityDelegate createReactActivityDelegate() {    return new ReactActivityDelegate(this, getMainComponentName()) {        @Override        protected Bundle getLaunchOptions() {            Intent intent = MainActivity.this.getIntent();            Bundle bundle = new Bundle();            Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);            if (imageUri != null) {                bundle.putString("image", imageUri.toString());            }else{                bundle.putString("image", "");            }            return bundle;        }    };}

Also, I am only receiving the image path when the app is closed, when it is already open in the background, it is not receiving the image file path.

How to fetch api data in Dropdown options in React Native expo Dynamically

$
0
0

I am new to React-Native and having some problems to fetch the api data in the dropdown List.Basically I want to fetch the names from the API and display it in the drop down .For a while i have added to countries .Below is my code for the same.I just want to fetch the name of the employee from the api .

import DropDownPicker from 'react-native-dropdown-picker';export default class ImageScreen extends React.Component {    static navigationOptions = ({ navigation }) => {    return {      title: "Source Listing",      headerStyle: {backgroundColor: "#000"},      headerTitleStyle: {textAlign: "center",flex: 1}     };    };    constructor(props) {     super(props);     this.state = {       loading: true,       dataSource:[]      };    }    componentDidMount(){    fetch("https://jsonplaceholder.typicode.com/users")  // **Api for fetching**    .then(response => response.json())    .then((responseJson)=> {      this.setState({       loading: false,       dataSource: responseJson      })    })    .catch(error=>console.log(error)) //to catch the errors if any    }    FlatListItemSeparator = () => {    return (<View style={{         height: .5,         width:"100%",         backgroundColor:"rgba(0,0,0,0.5)",    }}    />    );    }    renderItem=(data)=><TouchableOpacity style={styles.list}><Text style={styles.lightText}>{data.item.name}</Text><Text style={styles.lightText}>{data.item.email}</Text><Text style={styles.lightText}>{data.item.company.name}</Text></TouchableOpacity>    render(){     if(this.state.loading){      return( <View style={styles.loader}> <ActivityIndicator size="large" color="#0c9"/></View>    )}    return(<View style={styles.container}><ModernHeader title = "Contact us " /><DropDownPicker style = { {alignItems : "center"   , justifyContent :"center"}}  items={[        {label: {data.item.name}, value:  {data.item.name}} **Dropdown list option**    ]}    defaultValue={this.state.country}    containerStyle={{height: 50,width:375}}    style={{backgroundColor: '#fafafa',borderWidth: 4,    borderColor: "#ffa726",    borderRadius: 6,fontSize: 30}}    dropDownStyle={{backgroundColor: '#fafafa'}}    searchable={true}    searchablePlaceholder="Search..."    searchableError="Not Found"    onChangeItem={item => this.setState({        country: item.value    },    console.log(item.value)    )  }     /></View>    )}    }

enter image description here

Any Help is Appreiciated

The library com.google.firebase:firebase-iid is being requested by various other libraries at [[17.0.0,17.0.0]], but resolves to 16.2.0

$
0
0

I started to get this error today, yesterday everything worked fine, there was no changes in gradle or firebase version

The library com.google.firebase:firebase-iid is being requested by various other libraries at [[17.0.0,17.0.0]], but resolves to 16.2.0. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.

I saw that yesterday was update in google-services plugin, probably that is causing the problem.

How to fix this problem?

cd android && ./gradlew assembleRelease '.' is not recognized as an internal or external command, operable program or batch file

$
0
0

The official ReactJS documentation suggests to run the following command in the terminal for generating the release APK

cd android && ./gradlew assembleRelease

I get an exception in response to this command:

cd android && ./gradlew assembleRelease '.' is not recognized as an internal or external command, operable program or batch file.

What is an issue?

React Native Voice error on some Android phones

$
0
0

In one of the devices (Redmi A9), I have the output ofVoice.getSpeechRecognitionServices() ==> ["com.xiaomi.mibrain.speech"] and voice recognising is not working.Voice.start() ==> undefined butVoice.isAvailable() ==> trueVoice.isRecognizing() ==> true

but none of the following events are triggered,

Voice.onSpeechResultsVoice.onSpeechStartVoice.onSpeechEndVoice.onSpeechErrorVoice.onSpeechPartialResults

I tried again after installing Google App and now the device returns ["com.google.android.googlequicksearchbox", "com.xiaomi.mibrain.speech"] for Voice.getSpeechRecognitionServices() but voice is still not working. Permission is granted and I can record and play using @react-native-community/audio-toolkit.

Have anyone faced the similar issue and solved this? Any suggestions?


'installDebug' not found in root project 'android' React Native

$
0
0

I am trying to run my project on the android simulator. When I run react-native run-android I am getting the following:

FAILURE: Build failed with an exception.* What went wrong: Task 'installDebug' not found in root project 'android'.* Try: Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.BUILD FAILED

If I run ./gradlew tasks I get:

Build Setup tasks-----------------init - Initializes a new Gradle build. [incubating]wrapper - Generates Gradle wrapper files. [incubating]Help tasks----------buildEnvironment - Displays all buildscript dependencies declared in root project 'android'.components - Displays the components produced by root project 'android'. [incubating]dependencies - Displays all dependencies declared in root project 'android'.dependencyInsight - Displays the insight into a specific dependency in root project 'android'.help - Displays a help message.model - Displays the configuration model of root project 'android'. [incubating]projects - Displays the sub-projects of root project 'android'.properties - Displays the properties of root project 'android'.tasks - Displays the tasks runnable from root project 'android'.

Any idea why I don't have a installDebug task in my project? How do I get it back?

Other's side video is not showing in Twilio Video calling in react-native. Calling between Web and android

$
0
0

I'm using this library for twilio video calling https://github.com/blackuy/react-native-twilio-video-webrtcThe participant view is showing black after connection. I'm not getting any error. Values are coming in _onParticipantAddedVideoTrack. Other callbacks are working.

_onParticipantAddedVideoTrack = ({ participant, track }) => {    //console.warn("onParticipantAddedVideoTrack: ", participant, track)    console.log("conference 10 ", participant, track);    this.setState({      videoTracks: new Map([        ...this.state.videoTracks,        [track.trackSid, { participantSid: participant.sid, videoTrackSid: track.trackSid }]      ]),    });    this.setState({      trackSid: track.trackSid, isParticipant: true,      trackIdentifier: { participantSid: participant.sid, videoTrackSid: track.trackSid }    });  }<TwilioVideoParticipantView          style={styles.remoteVideo}          key={this.state.trackSid}          enabled={true}          trackIdentifier={this.state.trackIdentifier}        />

React Native adb reverse ENOENT

$
0
0

I am trying to get React-Native to work with Android V4.2.2 (Genymotion) but I am unable to test the app on the Emulator. When I ran react-native run-android, I get this error Could not run adb reverse: spawnSync

Here is a log

JS server already running.Running ~/Library/Android/sdk/platform-tools/adb reverse tcp:8081 tcp:8081Could not run adb reverse: spawnSync ~/Library/Android/sdk/platform-tools/adb ENOENTBuilding and installing the app on the device (cd android && ./gradlew installDebug...FAILURE: Build failed with an exception.* What went wrong:A problem occurred configuring project ':app'.> The SDK directory '~/Library/Android/sdk' does not exist.* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.BUILD FAILEDTotal time: 3.785 secsCould not install the app on the device, read the error above for details.Make sure you have an Android emulator running or a device connected and haveset up your Android development environment:https://facebook.github.io/react-native/docs/android-setup.html

NOTE: In the log it saids SDK directory does not exist, I have double check that I do have the SDK installed in that directory.

I found my android emulator when executing adb devices

List of devices attached192.168.56.101:5555 device

I have tried the following steps from Stack Overflow post, but still no luckhttps://stackoverflow.com/a/38536290/4540216

React Native android build failed. SDK location not found

$
0
0

I have error when i start running android

What went wrong:A problem occurred evaluating project ':app'.  > SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

React-native when runing android project take error

$
0
0

i take this error how can i solve this problem

When i run react-native project in android the emulator give a error.

Error message:TypeError : null is not an object(evuluating '_RNGestureHAndlerModule.default.Direction')

Error Message Screenshot

Making a drawer navigator for app with multiply files

$
0
0

I have the following error:"Another navigator is already registered for this container.You likely have multiple navigators under a single "NavigationContainer" or "Screen" ".

But as my app is a little specific, i couldn't find anything that really helped, i'm using typescript and i could only find examples on youtube by people using javascript. This is my code:

Main App.tsx:

const Stack = createStackNavigator();

const Drawer = createDrawerNavigator();

export default function App() {

return (

<NavigationContainer><Stack.Navigator   initialRouteName="Login"  screenOptions={{headerShown: false}}><Stack.Screen      name="Home"      component={Home}    /><Stack.Screen      name="Login"      component={Login}    /></Stack.Navigator><Drawer.Navigator   initialRouteName="Home"><Drawer.Screen       name="Home"       component={Home}     /><Drawer.Screen       name="Profile"       component={ProfileScreen}    /></Drawer.Navigator></NavigationContainer>

);

}

Home.tsx (this is where my drawer should be)

export default function Home({ navigation }) {

return(<KeyboardAvoidingView>            <View style={styles.container}><Header                placement="left"                centerComponent={{ text: 'i B l o c k',                 style: { color: '#fff', fontWeight: 'bold', fontSize: 20 } }}                rightComponent={{                     icon: 'menu',                     color: '#fff',                    onPress: ()=> navigation.openDrawer()                }}                containerStyle={{                    marginTop: -25,                    backgroundColor: '#87C8E1',                    justifyContent: 'space-around',                  }}            /><Image                style={styles.quadra}                source = {require('../../assets/quadra.png')}            /></View></KeyboardAvoidingView>)

}

and finally my ProfileScreen.tsx

export default function ProfileScreen({ navigation }) {

return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Button onPress={() => navigation.goBack()} title="Go back home" /></View>);

}

I'm new to React-Native, so i really don't realize what i'm doing wrong.

Debugging on external Android device via USB, but api requests do not show on network

$
0
0

I am Debugging my project on an external Android device via USB, i am making api requests and able to get response, however, i could not see the api request on network when i use "remote JS Debugging" on my chrome browser of my PC. can anyone give me some tips to make api requests show up on network?Here is what in the network


React Native sqlite storage does not open prepopulated database

$
0
0

I am using https://github.com/andpor/react-native-sqlite-storage for importing prepopulated data and these were my steps for setting it up:

1. npm install --save react-native-sqlite-storage

2. cd ios && pod install && cd ..

3. created 'www' folder and inserted 'users.db' in it. Then I added 'www' to my projectFolder as instructed

4. For android, I created an 'assets' folder in src/main and inserted the 'users.db' file into it.

However, I'm encountering an error where it says there is SQL ERROR: {"no such table: users", code 5}

I've tried multiple styles but to no avail.

import SQLite from 'react-native-sqlite-storage';...let db;...function loadAndQueryDB() {   //db = SQLite.openDatabase({ name: './users.db', createFromLocation: 1,}, openCB, errorCB);   //db = SQLite.openDatabase({ name: 'users.db', createFromLocation: 1,}, openCB, errorCB);   //db = SQLite.openDatabase({ name: 'users', createFromLocation: 1,}, openCB, errorCB);    queryUsers(db);}function queryUsers(db) {    db.transaction((tx) => {      tx.executeSql('SELECT * FROM users', [], queryUsersSuccess, errorCB);    });  }

My database has a table 'users' in it.

I'm not sure what the issue is and how to address it. Thanks!

EDIT: So I figured that

db = SQLite.openDatabase({name : "users.db", createFromLocation : 1}, openCB, errorCB);

Is opening from Library/Developer/CoreSimulator/Devices/.../LocalDatabase

How do I change where openDatabase is opening from?

View moves out of the screen when Text Input is focused used on Bottom Sheet in React Native for Android

$
0
0

I'm using the library - https://github.com/osdnk/react-native-reanimated-bottom-sheet

I'm using a TextInput on this bottom sheet. And now when the Text Input is focused or typed in, the bottom sheet should remain at the same position. It works fine for iOS, shown in the below screenshot.

enter image description here

And when I focus the Text Input on Android, the bottom sheet moves up along with the keyboard, shown in below 2 screenshots.

(Bottom Sheet in Android not focused)

enter image description here

(Bottom Sheet in Android focused)

enter image description here

I've also tried wrapping my bottom sheet inside KeyboardAvoidingView and its props accordingly but it didn't work.

Expo only working on web and fails on Android with multiple issues

$
0
0

My project is mainly based on this boilerplate. To not get into trouble with the deployments later on, I'm using expo.

Now I'm just wondering why the deployment to Android is not working. When I deploy it to web it works great without any trouble. But doing expo android deploy gives me expo android log and this on the Android Emulator:

android emulator error

But the project structure is clean and that index.css is working properly

project structure

What is the difference between a Run in web and Run on android?

Also when I just remove that index.css for testing. Web still works but without styles. But on Android I now get another error on my used localstorage.

I know there is a difference between react-native and react-web. But I was thinking that expo is able to handle this. Maybe I was expecting too much from expo? So am I wrong with that and all is fine. And all I have to do is making it work on Android, like fixing the index.css issue and the localstorage? Or is there a smarter way to get my obviously react-web application to work on my Android device?

How do i pass data from one component to another in realtime?

$
0
0

I am trying to pass data that I pull from a SQLDatabase into another component that would display it. I'm not sure how to do it exactly...

In my App.js

This calls CustomList

import CustomList from './components/FlatList';export default function App() {  return(<CustomList />  );};

which

In my CustomList

import Data from './Data';...export default function CustomList() {    //Sets up Getter , Setter , Initial Data    const [data, setData] = useState(Data);    ...    return (<FlatList             ListHeaderComponent = {header}            data = {data}            keyExtractor = { (item) => (item.id).toString()}            ItemSeparatorComponent = { () => <View style={styles.itemSeparator}></View>}            contentContainerStyle={ {borderBottomColor:'grey', borderBottomWidth: 1} }            renderItem = { ({item, index}) => <ListItem item={item} index={index}/>}       />...

The CustomList above works if I import hard-coded data below

In my Data.js

const Data = [    {id: 1, text: 'Boadb'},    {id: 2, text: 'Joe'},    {id: 3, text: 'Jane'},    {id: 4, text: 'John'},    {id: 5, text: 'Janet'},    {id: 6, text: 'Janet'},    {id: 7, text: 'Janet'},    {id: 8, text: 'Janet'},];export default Data;

However, I want a real-time syncing database that will update the CustomList whenever changes are made.

In my SQLData.js

let helperArray;...export default function SQLData() {     ...     function querySuccess(tx, results) {         ...         helperArray = [];         //Go through each item in dataset         for (let i = 0; i < len; i++) {         let row = results.rows.item(i);         helperArray.push(row);      }    ...    return ();  };

As you can see from the code above, I have put the data pulled from the SQLDatabase into a variable helperArray. I was wondering how do I import it similarly like 'Data.js' and have it output the same way! Thanks

Task :react-native-webview:compileDebugJavaWithJavac FAILED

$
0
0

I keep getting this error, when I try running my React Native application after installing the react-native.webview package. Please what could I be doing wrong.

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.Jetifier found 1135 file(s) to forward-jetify. Using 8 workers...info Starting JS server...info Installing the app...Starting a Gradle Daemon, 1 busy Daemon could not be reused, use --status for details> Task :react-native-webview:compileDebugJavaWithJavac> Task :react-native-webview:compileDebugJavaWithJavac FAILEDDeprecated 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_warnings79 actionable tasks: 14 executed, 65 up-to-dateC:\Projects\React-Native\FUNAI\node_modules\react-native-webview\android\src\main\java\com\reactnativecommunity\webview\RNCWebViewModule.java:276: error: cannot find symbol    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {                                                    ^  symbol:   variable Q  location: class VERSION_CODESNote: C:\Projects\React-Native\FUNAI\node_modules\react-native-webview\android\src\main\java\com\reactnativecommunity\webview\RNCWebViewManager.java uses or overrides a deprecated API.Note: Recompile with -Xlint:deprecation for details.Note: C:\Projects\React-Native\FUNAI\node_modules\react-native-webview\android\src\main\java\com\reactnativecommunity\webview\RNCWebViewManager.java uses unchecked or unsafe operations.Note: Recompile with -Xlint:unchecked for details.1 errorFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':react-native-webview:compileDebugJavaWithJavac'.> Compilation failed; see the compiler error output for details.* 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 1m 37serror 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=8081C:\Projects\React-Native\FUNAI\node_modules\react-native-webview\android\src\main\java\com\reactnativecommunity\webview\RNCWebViewModule.java:276: error: cannot find symbol    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {                                                    ^  symbol:   variable Q  location: class VERSION_CODESNote: C:\Projects\React-Native\FUNAI\node_modules\react-native-webview\android\src\main\java\com\reactnativecommunity\webview\RNCWebViewManager.java uses or overrides a deprecated API.Note: Recompile with -Xlint:deprecation for details.Note: C:\Projects\React-Native\FUNAI\node_modules\react-native-webview\android\src\main\java\com\reactnativecommunity\webview\RNCWebViewManager.java uses unchecked or unsafe operations.Note: Recompile with -Xlint:unchecked for details.1 errorFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':react-native-webview:compileDebugJavaWithJavac'.> Compilation failed; see the compiler error output for details.* 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 1m 37s    at makeError (C:\Projects\React-Native\FUNAI\node_modules\execa\index.js:174:9)    at Promise.all.then.arr (C:\Projects\React-Native\FUNAI\node_modules\execa\index.js:278:16)    at process._tickCallback (internal/process/next_tick.js:68:7)
Viewing all 28482 articles
Browse latest View live