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

Width of multiline React-Native Text component won't resize to length of longest line of text on Android

$
0
0

I have a multiline React-Native Text component whose width should auto-adjust to the width of the longest line of text. This is working on iOS but not on Android, and I'm not sure why.

Please see this expo snack for a demo.on iOS it looks like this:

enter image description here

on Android it looks like this:

enter image description here

The demo above is just a stripped down excerpt from the full app. I need to keep flexDirection: 'row' because in the full app there are other items I need to display to the right of this textbox.


App is crashing while calling interstitialAd.load() method in React-Native

$
0
0

I am trying to place interstitialAd in my project but the interstitialAd.load(); is crashing the app. My AdMob config is fine ad Banner ads are working perfectly.

Used Plugin: @react-native-firebase/admob

Here is the code:

import { Button, View } from 'react-native';import { InterstitialAd, AdEventType, TestIds } from '@react-native-firebase/admob';export default class InterstitialAdUnit extends React.Component {    constructor(props) {        super(props);    }    showInterstitialAd = () => {        const interstitialAd = InterstitialAd.createForAdRequest(TestIds.INTERSTITIAL);        interstitialAd.onAdEvent((type, error) => {                       if (type === AdEventType.LOADED) {                interstitialAd.show();            }        });        interstitialAd.load();    }     render() {        return (<Button                title="Show Interstitial"                onPress={() => {                    this.showInterstitialAd();                }}            />        )}}

React native app with android native player

$
0
0

I have a react native app running in Android TV. For an administerial decision I cannot use a react native player, I have to use an android native player; Im a JS developer and I have zero experience in android, so Id like to know first of all if this is actually possible and if there`s a way to play live content in multicast.

Thanks in advance!!

Android get the device battery level accurate to decimal level

$
0
0

For Android application i need battery level accurate to the 2 decimal value. How can i get the battery level accurate to the two decimal value?

ArSceneView SEGFAULT

$
0
0

App crashes randomly after starting/resuming a "session"

Seems like this is the main error

JNI ERROR (app bug): global reference table overflow (max=51200)global reference table dump

React native Ctrl M or dev tool not showing in my emulator

$
0
0

He thanks in advance,In react native am not able to right click or open dev mode in emulator.

Struggling to get Android build working due to minSdkVersion

$
0
0

I think I must be missing something here, as far as I'm aware I've tried these approaches after reading a number of articles and I can't seem to get things working. I'm triggering these builds manually at the moment, using the command that detox would use which is ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug though I've also tried using npx detox build --configuration android.emu.debug directly too.

My error is a typical minSdkVersion mismatch:

uses-sdk:minSdkVersion 16 cannot be smaller than version 21 declared in library [com.facebook.react:react-native:0.64.0] /home/iw651/.gradle/caches/transforms-2/files-2.1/354c8f3d479b5a1203bfff874da058bc/jetified-react-native-0.64.0/AndroidManifest.xml as the library might be using APIs not available in 16        Suggestion: use a compatible library with a minSdk of at most 16,                or increase this project's minSdk version to at least 21,                or use tools:overrideLibrary="com.facebook.react" to force usage (may lead to runtime failures)

build.gradle
So the things that are confusing me somewhat, are firstly my project's minSdkVersion is set to at least 21... This is the top of my /android/build.gradle file:

buildscript {    ext {        buildToolsVersion = "29.0.3"        minSdkVersion = 23        compileSdkVersion = 29        targetSdkVersion = 29        kotlinVersion = '1.3.61'        ndkVersion = "20.1.5948944"    }

Within my android/app/build.gradle I have the following:

defaultConfig {     minSdkVersion rootProject.ext.minSdkVersion     targetSdkVersion rootProject.ext.targetSdkVersion     multiDexEnabled true     ...}

So really I believe the following has been done. But it's obviously still throwing an error.

or increase this project's minSdk version to at least 2

tools:overrideLibrary
I'm not exactly sure how to do this, I've tried setting this in my /android/app/src/debug/AndroidManifest.xml file. I've tried a few permutations:

<uses-sdk minSdkVersion="16" tools:overrideLibrary="com.facebook.react"/>
<uses-sdk minSdkVersion="21" tools:overrideLibrary="com.facebook.react"/>
<uses-sdk tools:overrideLibrary="com.facebook.react"/>

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/><uses-sdk minSdkVersion="16" tools:overrideLibrary="com.facebook.react"/><application            android:usesCleartextTraffic="true"            tools:targetApi="28"            tools:ignore="GoogleAppIndexingWarning"><activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /></application></manifest>

None of those permutations seem to help either.

use a compatible library with a minSdk of at most 16
This just leaves me with this option, for which I'm going to raise a PR against the package in question. But it still doesn't help me build until a new release is made.

Can anyone see what I'm missing? Or could some caching be getting in the way between builds?

delay in react native's native module (android)

$
0
0

I am retrieving google fit data using React Native's Native Modules.
The logic works fine and i get my expected result.
The issue is with the delay in retrieval.
I click a Button on my app and it calls the Native Module method as shown below

js file:

click = async() => {await NativeModules.MyHealth.getHealthData((err ,result) => {        let res = JSON.parse(result)        let unique = _.uniqWith(res?.HealthData, _.isEqual);        this.setState({hd: [...unique], full: true})        console.log("HD:", this.state.hd)      //returns empty for first click. second click i get all the values    });}

In my ReactModule.java

 @ReactMethod    public void getHealthData(Callback cb) {        try{            final Activity activity = getCurrentActivity();            if(activity != null && activity instanceof MainActivity){                JSONObject obj = ((MainActivity) activity).getHealthValues();  //main method                cb.invoke(null, String.valueOf(obj));            }        }catch (Exception e){            Log.i("error", "error here!!!!");            cb.invoke(e.toString(), null);        }    }

MainActivity.java

  public JSONObject getHealthValues() {        readHistoryData();     //runs my Fitness.getHistoryClient query        return json;    }

I am trying to figure out why the data doesn't flow to the front-end js file with the first click. But then i get the data with the second click.
Anyone has any clue about this behaviour??


how to access photo react native webview input file android

RadioButton React Native Paper set IOS style in android

$
0
0

I'm using RadionButton from react-native-paper library. For android I have such style enter image description here

Is it possible to set RadioButton style in Adroid such as IOS style (icon "checked")? Thanks in andvance for your answer.

Call-Recording with new devices [closed]

$
0
0

I want to create an app that records all calls automatically also supported in new devices also . Any one please help it's urgent..

React native TouchableOpacity onPress not working on Android

$
0
0

TouchabelOpacity works fine on iOS but the onPress method does not work on Android for me.

My react-native version: 0.57.4

My code:

const initDrawer = navigation => (<TouchableOpacity    style={{ left: 16 }}    onPress={() => onPressDrawerButton(navigation)}><Ionicons name="ios-menu" color="white" size={30} /></TouchableOpacity>);

react-native-contacts android null is not an object evaluating t.givenName[0]

$
0
0

I'm using react-native-contacts to get user contacts and mostly it works well except few android devices that return the error null is not an object evaluating t.givenName[0]. I'm 100 percent sure that the user gave permission on reading contacts so I don't know how to handle that because it's critically important for my app to have access to contacts.

Any help welcome. Thanks in advance

Activating google password manager prompt @ React-Native app

$
0
0

I'm developing a new app for android with React-Native 0.63.4 and I want google services to prompt storing users credentials with google password manager. I'm using Formik to manage my form actions.

Here is the code:

<View style={styles.formContainer}><Input                onChangeText={handleChange('email')}                onBlur={(e) => {                  handleBlur('email')(e);                }}                placeholder={emailPlaceholder}                autoCompleteType="email"                autoCapitalize="none"                keyboardType="email-address"                textContentType="emailAddress"                value={values.email}                isError={Boolean(errors.email && touched.email)}                errorMessage={errors.email}              /><PasswordInput                placeholder={passwordPlaceholder}                notFocusedText={continueToResetPassword}                textContentType="password"                onChangeText={handleChange('password')}                onBlur={(e) => {                  handleBlur('password')(e);                }}                value={values.password}                isError={Boolean(errors.password && touched.password)}                errorMessage={errors.password}                notFocusedTextOnPress={() =>                  navigation.navigate('EnterEmail', {                    email: values.email,                  })                }              /><Button text={isSubmitting ? '' : button} onPress={handleSubmit}>                {isSubmitting ? <ActivityIndicator color="black" /> : null}</Button></View>

Both <Input /> and <PasswordInput /> inherit from React-Native's <TextInput /> element and forward the {...props} as a last line before ">".

Props as textContentType and autoCompleteType are set, but I still don't have a prompt to store the credentials, what am I missing?

p.s. Other native apps are definitely prompted after a successful login, same way it's implemented in most web browsers. The question is how it's implemented in react-native if at all?

How to get a notification automatically processed by the app when received in HMS Push Kit and React Native?

$
0
0

I am using react-native v0.61.5 and latest versions of react-native-hms-push (App) and hms-push-serverdemo-nodejs.

My server app is able to send both Notification Messages both Data Messages.

What is unclear to me, is how messages must be implemented in order to have this:

  1. when app is in a killed state: a messages is received, sounds on and a bubble appears, the user taps on the notification bubble, the App processes the notification payload while opening

  2. when app is in a killed state: a messages is received, sounds on and a bubble appears, the user opens the App without tapping on the notification bubble, the App processes the notification payload while opening

  3. when app is in a background state: a messages is received, sounds on and a bubble appears, the user opens the App without tapping on the notification bubble, the App processes the notification payload while opening

  4. when app is in background state: a messages is received, sounds on and a bubble appears, the user opens the App without tapping on the notification bubble, the user opens the App without tapping on the notification bubble, the App processes the notification payload while opening

  5. when app is in foreground state: a messages is received, sounds on and a bubble DOES NOT appears, (there are no bubbles to be tapped), the App processes the notification payload suddenly

We encountered some difficulties to satisfy all these 5 requirements listed above. What we have to send from server-side? Data Messages or Notification Messages?

We also tried to use:

let message = {      notification: {...},      android: {androidConfig..., notification: {foreground_show: [false|true]}},      token: new Array(pushDeviceToken)  };

both:

let message = {      data: notification,      android: {androidConfig..., notification: {foreground_show: [false|true]}},      token: new Array(pushDeviceToken)  };

But is seems that there is no the best option...

One more thing: it seems that foreground_show does not works for Notification Messages, when I keep the App in opened state and send a Notification Message with foreground_show: true, no bubble appears and the notification is not processed by the App.

The cause could also be a bad configuration on the App side. It is not very clear how to configure it, since we are new to HMS Push Kit.


React native: Token issue from auth0 2 suddenly become invalid during debugging session

$
0
0

I have a server that running with asp.net. I follow a tutorial from the web that enable my server to issue a token Auth0 2 to the client that request it and created web api so that my android emulator able to retrieve some data from the server. I set my token expired date to 365 days. I try to request a token from Postman by providing grant_type, username and password and as expected server return me a token and I use the Get method from Postman to fetch some data from an API endpoint and submit the token in the header, as expected the server successfully return me the data without any problem. The Postman able to fetch data from the server by using a token issue from yesterday so I assume the token implementation is correct.

Server:

    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()    {        AllowInsecureHttp = true,        TokenEndpointPath = new PathString("/token"),        AccessTokenExpireTimeSpan = TimeSpan.FromDays(365),        Provider = new SimpleAuthorizationServerProvider()    };        // Token Generation        app.UseOAuthAuthorizationServer(OAuthServerOptions);        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());        app.UseOAuthBearerTokens(OAuthServerOptions);

Android react native :Login to get an access token from the server

  var formBody="grant_type=password&username="+userEmail+"&password="+userPassword;  fetch('http://aaa.aaaa.com/token', {  method: 'POST',  body: formBody,  headers: {    //Header Defination'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',  },})  .then((response) => response.json())  .then((responseJson) => {    //Hide Loader    setLoading(false);    console.log(responseJson);    // If server response message same as Data Matched    //if (responseJson.status == 1)     if (responseJson.access_token)     {      global.token=responseJson.access_token;      AsyncStorage.setItem('access_token', responseJson.access_token);      //console.log(responseJson.data[0].user_id);      //navigation.replace('DrawerNavigationRoutes');      navigation.navigate('NavigatorHome');    } else {      //AsyncStorage.setItem('user_id', 'test1');      //navigation.navigate('NavigatorHome');      //setErrortext('Please check your email id or password');      console.log('Please check your email id or password');    }  })  .catch((error) => {    //Hide Loader    setLoading(false);    console.error(error);  });

Fetch Data from API endpoint

      var accessToken=global.token;      var formBody="";      formBody = JSON.stringify({'module': 'order','action': 'get','value':route.params.orderID      })    fetch('http://aaa.aaaa.com/api/Orders?ID='+formBody, {        method: 'Get',        headers: {          //Header Defination          Accept: 'application/json',              'Content-Type': 'application/json','Authorization': 'Bearer '+ accessToken,        },      })      .then((response) => response.json())      .then((responseJson) => {          //Hide Loader          //setLoading(false);          console.log(responseJson);          // If server response message same as Data Matched          //if (responseJson.status == 1)         })        .catch((error) => {          //Hide Loader          //setLoading(false);          console.error(error);        });        

After that I try to run with android emulator. First I use the fetch method by providing grant_type, username and password, as expected the server return me a token and I store it with AsyncStorage. Then I try to fetch some data by providing the token I requested previously and server able to return me the data without any problem. But if I leave my emulator like for 15min or 30min, now when I try to fetch data from the server it fail. What I do is I try to request a new token by sending grant_type, username and password again and the new token work as expected.

This is weird! I have double check my access token setting at the server which is 365 days and Postman able to Get data without any problem by using the token that issue yesterday, why did the token that issued to my emulator expired within 15 or 30 min? Hope some body can point out my problem. Thanks in advance!

React Navigation 'beforeRemove' event is not getting fired in React Native

$
0
0

I am trying to prevent user from going back by Android back button or gesture while a video is being recorded in React Native. As per documentation of React Navigation, it should be handled with the beforeRemove event listener. But the event is never being fired when going back.

I tried with blur, it was getting fired though, but since this event doesn't have a preventDefault() method, it's not usable in this scenario.

React Navigation - v5.x

React Native - 0.63.2

Here's the sample code for the screen I am trying to achieve

const VideoCapturePage = ({navigation}) => {  const [isRecording, setIsRecording] = useState(false);  useEffect(() => {    navigation.addListener('beforeRemove', (e) => {      if (!isRecording) {        return;      }      e.preventDefault();      Alert.alert('Unsaved changes','There are unsaved changes. Please chose what you want.',        [          {            text: 'Go back',            onPress: () => {              navigation.dispatch(e.data.action);            },          },          {            text: 'Cancel',            onPress: () => {              console.log('cancelled');            },          },          {            text: 'Continue to Edit',            onPress: () => {              console.log('continue');            },          },        ],        {          cancelable: false,        },      );    });  }, [navigation, isRecording]);  return (<View style={styles.container}><VideoCamera        isRecording={isRecording}        setIsRecording={setIsRecording}      /></View>  );};

Error while trying to run Reactive Native: Run Android on device in VSC

$
0
0

So I am trying to start react native project on my phone, but I got this error:

Stack: Error: Failed to run the application in Android (error code 104): Error while executing command '"\Users\mac\Library\Android\sdk\platform-tools\adb" devices': Command failed: "\Users\mac\Library\Android\sdk\platform-tools\adb" devicesThe system cannot find the path specified.

I am using Visual Studio Code, and command React Native: Run Android on device from React Native tools

react native svg onpress does not work for android with a large viewBox

$
0
0

Im using the react-native-svg module with expo. I have tried it on a bare project no expo with latest everything, same issue.

When I use a very large viewbox like below, the onPress functionality does not work for elements. Example below seems to work fine on iOS and Web. I have tested to the point where I know it has nothing to do with the grouping or the matrix transformation.

<Svg  height="1920"  width="1080"  fill="none"  viewBox="2942852.602193035 -472992.4195375803 897.8977111047134 1329.2074627304683"  preserveAspectRatio='none'><G transform="matrix(1,0,0,-1,0,0)"><Rect x="2943049.34094599" y="472319.3465770291" width="300" height="300"               fill="blue" onPress={()=>{alert('achoo!')}}/> </G></Svg>

Please test and let me know what you think. onPress works fine with a more 'traditional' viewBox. For some reason does not work with the example above on android but works on iOS and web.

Dangerous Permissions is auto granted at app install in new project [React Native - Android]

$
0
0

I have installed awesome project from react native cli and run it in android build.It works fine.

When I added, below dangerous permission

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

in my android manifest.xml and run the project it is auto granted on app install.

I check app info and it is granted by default.

Note:

  • Min Version : 23
  • Target and Compile Version : 29
  • React Native Version: 0.64.0

So when I check permission programmatically it is always granted. It should not.

Viewing all 29478 articles
Browse latest View live


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