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

React Native - Android Emulator Device

$
0
0

For several hours now, I have tried to change the emulator that Android uses with no luck, the application will launch and run fine on the default Nexus 5. by using react-native run-android. but trying to run it on another emulator crashes, If I try to build from Android Studio, it will not connect to Metro.

I either launch the emulator in Android studio and it won't connect to the Metro bundler.

Or I launch it from the command line with CLI react-native run-android and it launches Nexus 5 and I can't do shit.

Why can't the emulators easier like ios (facepalm).

Please help me easily launch my react native app on a different emulator than the default. It's outrageous this is not a choice or option. I have tried for hours.


React Native Fetch command returns JSON on debug builds, but not release builds

$
0
0

I have an issue with react native where the debug build can successfully fetch JSON data using fetch from a server / API, but my release build does not. I have tried using useEffect as well as creating functions on onClick to retrieve data, but nothing seems to work. It either crashes and adb logcat says that phoneDetails or setPhoneDetails are undefined.

  let [phoneDetails, setPhoneDetails] = useState([]);  let PhoneModel = 'VOG-L09';//Huawei P30 pro  let saveJSON;  useEffect(() => {    fetch('API Call') //This gets JSON data from a server, specifically, the phone model and extra device info.      .then(response => response.json())      .then(json => setPhoneDetails(json));//Also have tried:      .then(json => (saveJSON = json));//Then calling stringify on an alert to check if data is there.  }, [PhoneModel]);

I have also tried using a simple async function using await similar to the code above but it doesn't work.

How to load a database to a user app in react native

$
0
0

I am building an app that shows quotes and small texts to an user daily and I am already using async storage to store user preferences. Though I need a way to store these hundreds of quotes too. As well as recall one every day for the notification and everytime the user asks for a new one. I could just write it all on an object in the code in a file for it and import everywhere I need it but that doesn't sound like a good option or load it all in async to be recovered when needed like my user preferences. But I can't tell yet which since I am new to RN.

How to add App Shortcuts into React Native project

$
0
0

I've been seen on Android we have something like this:React Native App Shortcuts

So, I was wondering if I could do something like that in react native cli, no expo.

Native UI Component bridging not working React Native

$
0
0

I was following this guide "https://medium.com/47billion/how-to-develop-android-ui-component-for-react-native-fddd141f5ae4" that creates a simple native android UI component and bridging it to RN but it doesn't work so I amendmended it to become a simple TextView just to try out whether the bridging process works. Are there any reliable and simple tutorials on creating a native UI component and bridging to RN for usage? Below is my code:-

NativeTextManager.javapublic class NativeTextManager extends SimpleViewManager<TextView> {    public static final String REACT_CLASS = "NativeText";    @Override    public String getName() {        return REACT_CLASS;    }    @Override    protected TextView createViewInstance(ThemedReactContext reactContext) {        TextView textView = new TextView(reactContext);        textView.setTextSize(30);        textView.setText("YOYOYOYO");        System.out.println("test view "+textView);        return textView;    }}

NativeTextManager.java just returns a simple TextView with a hardcoded text of "YOYOYO", the console prints the textView component but on my RN side the TextView from java doesn't get rendered...

NativeTextPackage.javapublic class NativeTextPackage implements ReactPackage {    @Override    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {        return Collections.emptyList();    }    @Override    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {        return Collections.<ViewManager>singletonList(                new NativeTextManager()        );    }}

ON REACT NATIVE SIDE:-

NativeText.jsimport { requireNativeComponent } from 'react-native';module.exports = requireNativeComponent("NativeText");

In my app.js I just use my NativeText component as below but it doesnt get rendered... I have already added my package to MainApplication.java with "packages.add(new NativeTextPackage());"

App.js<NativeText />

How to Connect native android / Kotlin functionality to react native?

$
0
0

I have implemented SMSBroadcast Receiver functionality in native android (Kotlin) code.

The functionality is like whenever a new text message (SMS) is received I need to call an api (even the app is in background).

When i run as standalone android application its working fine. But how to integrate this with my react-native app?

The below is the code i wrote natively.

import android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.telephony.SmsMessageimport android.util.Logimport android.widget.Toastimport com.reactnativecommunity.asyncstorage.AsyncLocalStorageUtilimport com.reactnativecommunity.asyncstorage.ReactDatabaseSupplierclass SMSBroadcastReceiver : BroadcastReceiver() {    override fun onReceive(context: Context, intent: Intent) {        Log.i(            TAG,"Intent received: "+ intent.action        )        if (intent.action === SMS_RECEIVED) {            val bundle = intent.extras            var data = ""            if (bundle != null) {                val pdus =                    bundle["pdus"] as Array<Any>?                val messages =                    arrayOfNulls<SmsMessage>(pdus!!.size)                for (i in pdus.indices) {                    messages[i] =                        SmsMessage.createFromPdu(pdus[i] as ByteArray)                }                if (messages.size > -1) {                    data = messages[0]!!.messageBody                    Log.i(                        TAG,"Message recieved: $data"                    )                }            }            Toast.makeText(context,"Message received : $data", Toast.LENGTH_LONG).show()//            var accessToken = AsyncLocalStorageUtil.getItemImpl(ReactDatabaseSupplier.getInstance(context).get(), "");//            if (accessToken != null){//                //            }            if(listener!= null)            {                listener?.onSmsReceive(data)            }        }    }    companion object {        private const val SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"        private const val TAG = "SMSBroadcastReceiver"        var listener : OnCustomSmsListener ?= null    }}

** Package suggestions are also welcome **

React Native app doesn't have network connection when enable remote js debugging

$
0
0

I almost spent whole day to search everywhere, tried to figure out this but no luck.

I used my cell phone samsung S10 installed android10 for android app dev under React Native. Usually I just connect my cell phone to my pc, cd into my project, run 'react-native run android', wait for the metro bundler start up and loading, then app was installed in my cell phone, most of the time I enable 'remote JS debugging' and code based on the chrome console log, everything was smooth.

All the sudden, one day after enabling 'remote JS debugging' as usuall, the app kept tell that 'no internet connection', and from the chrome console, every requests were all timed out. I didn't do any modification/configuration either in my phone or my pc dev environment, and the data server worked good as well at that time.

I have two RN app projects, one is RN 0.55 and the other is RN 0.62, this happens on both so it is not related with RN.

I tried in different PC with the same cell phone, issue both happened, so it's not realted with PC dev environment.

I tried another cell phone then everything works correctly so it is obviousely something wrong in my samsung S10, although I didn't change anything but I still went through all the config especially in developer options, USB debuggin is on, USB configuration is 'Transferring files/Android Auto' as usual, nothing looks fishy or wrong.

This is weird, the app in my S10 cell phone can't connect to network when it is operated in 'remote JS debugging', can anybody help me out or give some hint here? Thanks a lot!

This merchant is not enabled for Google Pay. [Android, React-Native]

$
0
0

i need to integrate android/google Pay in my app. used react-native-payments for integrate native payment wallet.

Sheet open in type os TEST mode but in release mode give error Like This merchant is not enabled for Google Pay.

already generate merchantId in Play store console and try to run app from beta testing.

how can i enable google pay?? i can't find.

Thanks in advance...


Images for Multiple Screen Densities on React Native

$
0
0

React Native Docs told:

You can also use the @2x and @3x suffixes to provide images for different screen densities. If you have the following file structure:

.├── button.js└── img├── check.png├── check@2x.png└── check@3x.png

the bundler will bundle and serve the image corresponding to device's screen density.

And Android App Bundle Docs told,

Google Play then uses the app bundle to generate the various APKs that are served to users, such as the base APK, dynamic feature APKs, configuration APKs, and (for devices that do not support split APKs) multi-APKs. AAB Result

I have multiple images that support different screen densities (img.png, img@2x.png, etc). If I build application in .aab format, did my different-screen-densities-images will be separated and placed on different asset pack based on screen densities?

How to update adjacent tab from a BottomTabNavigator tab in React native

$
0
0

Im using react-navigation for react native. I have three screens inside a bottomtabnavigator. One of them contains a location picker(for eg.). I want to update the location details in the two other pages too whenever user picks a new location. How can i listen for location change from adjacent tabs?

React Native deeplinking and android:launchMode problem

$
0
0

I have been trying deeplinking in a react-native application and trying to directly open a screen inside a navigator. I use react-native-deep-linking and react-navigation as libraries. Also nested navigators are used. Deeplinking works correctly except I have some problems with the android:launchMode property.

This is the results I get for each of the android:launchMode options.

  • android:launchMode="standard" - App opens using the deeplink but opens up an entirely new application.
  • android:launchMode="singleTask" - App opens using the deeplink. If I open the app using another link. App comes to the foreground but it directs to the previous link.
  • android:launchMode="singleTop" - App opens using the deeplink but opens up an entirely new application.
  • android:launchMode="singleInstance" - App opens using the deeplink but opens up an entirely new application.

If I remove the android:launchMode property, again the same thing happens as the "standard" mode because it is the default.

What option can I use to resolve this problem? Is there any @override that I can do inside the main activity?

Below is my AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><application        android:name=".MainApplication"        android:label="@string/app_name"        android:icon="@mipmap/ic_launcher"        android:roundIcon="@mipmap/ic_launcher_round"        android:allowBackup="false"        android:theme="@style/AppTheme"><activity            android:name=".MainActivity"            android:launchMode="singleTask"            android:label="@string/app_name"            android:screenOrientation="portrait"            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"            android:windowSoftInputMode="adjustResize"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter><intent-filter><action android:name="android.intent.action.VIEW"/><category android:name="android.intent.category.DEFAULT"/><category android:name="android.intent.category.BROWSABLE"/><category android:name="android.intent.category.VIEW"/><data android:scheme="https" android:host="*.myapplive.com" android:pathPrefix="/"/><data android:scheme="https" android:host="*.myapp.com" android:pathPrefix="/"/></intent-filter></activity><activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/></application>

What is the difference between react-native cli and Expo with Bare workflow?

$
0
0

I am going to build a very big application with multiple complex functionalities. but I am stuck on bellow points -

  1. What is the difference between react-native cli and Expo with Bare workflow?
  2. what Should I include in my project and why?
  3. is expo created by facebook?

Not able to run react native app in Android Emulator - using EXPO cli

$
0
0

Installed the expo cli using "npm install -g expo-cli" and create a project expo init AwesomeProject.I have the android emulator running ,see the installed version in the image

but when i try to run the expo project using "npm run android" getting error as Couldn't start project on Android: Error running adb: unable to get local issuer certificate
can any one help me on this thanks..SDK toolsSDk platformerror image

Debugging in android studio - React Native APP

$
0
0

I have a React Native app that is spitting out an error in Android. iOS is fine.Using the app file I am TRYING to debug the issue.In android studio, I installed the apk file in the emulator.ow I can see in Logs the error is:

2020-06-10 17:42:11.238 4692-4835/hk.org.ha.testhago E/unknown:ReactNative: Exception in native call java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String at com.facebook.react.bridge.ReadableNativeArray.getString(Unknown Source:21) at com.facebook.react.bridge.JavaMethodWrapper$5.extractArgument(Unknown Source:0) at com.facebook.react.bridge.JavaMethodWrapper$5.extractArgument(Unknown Source:0) at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:162) at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:23) at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0) at android.os.Looper.loop(Looper.java:193) at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37) at java.lang.Thread.run(Thread.java:764)

How on earth do I find this in my code? I have so many java files!! I tried with a watchpoint for"java.lang.double" well it didn't work.What else can I do?

Android Splash Screen shifts

$
0
0

I have an Android Splash Screen which renders a drawable. When it is opened via a cold start, I find that my asset simply shifts in an upward direction.

You can find the appropriate code below, all unnecessary code has been omitted.

Here's the slight shift:

enter image description here

SplashActivity.java

public class SplashActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        Intent intent = new Intent(this, MainActivity.class);        startActivity(intent);        finish();    }}

MainActivity.java

@Overrideprotected void onCreate(Bundle savedInstanceState) {    SplashScreen.show(this, R.style.SplashTheme);    super.onCreate(savedInstanceState);}

res/drawable/background_splash.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque"><item android:drawable="@color/splash_background_color"/><item        android:gravity="center"><bitmap            android:src="@drawable/x150"/></item></layer-list>

res/layout/launch_screen.xml

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@color/splash_background_color"><ImageView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:src="@drawable/background_splash"        /></FrameLayout>

res/values/styles.xml

<resources><!-- Base application theme. --><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --></style><style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar"><item name="android:windowBackground">@drawable/background_splash</item></style></resources>

Android-studio ERROR: Cannot add task 'copyDebugIconFonts' as a task with that name already exists

$
0
0

I have React Native project. When i build Android version i get an ERROR: Cannot add task 'copyDebugIconFonts' as a task with that name already exists. And in my terminal i have this error: FAILURE: Build failed with an exception.

  • Where:Script '/Users/evgeniykireev/openCalls/node_modules/react-native-vector-icons/fonts.gradle' line: 16

  • What went wrong:Cannot add task 'copyDebugIconFonts' as a task with that name already exists.

My build.gradle:

buildscript {    ext {        buildToolsVersion = "28.0.3"        minSdkVersion = 16        compileSdkVersion = 28        targetSdkVersion = 28        supportLibVersion = "28.0.0"    }    repositories {        google()        jcenter()    }    dependencies {        classpath("com.android.tools.build:gradle:3.4.1")        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        mavenLocal()        maven {            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm            url("$rootDir/../node_modules/react-native/android")        }        maven {            // Android JSC is installed from npm            url("$rootDir/../node_modules/jsc-android/dist")        }        google()        jcenter()    }}

My fonts.gradle:

def config = project.hasProperty("vectoricons") ? project.vectoricons : [];def iconFontsDir = config.iconFontsDir ?: "../../node_modules/react-native-vector-icons/Fonts";def iconFontNames = config.iconFontNames ?: [ "*.ttf" ];gradle.projectsEvaluated {    android.applicationVariants.all { def variant ->        def targetName = variant.name.capitalize()        def targetPath = variant.dirName        // Create task for copying fonts        def currentFontTask = tasks.create(                name: "copy${targetName}IconFonts",                type: Copy) {            into("${buildDir}/intermediates")            iconFontNames.each { fontName ->              from(iconFontsDir) {                include(fontName)                into("assets/${targetPath}/fonts/")              }              // Workaround for Android Gradle Plugin 3.2+ new asset directory              from(iconFontsDir) {                include(fontName)                into("merged_assets/${variant.name}/merge${targetName}Assets/out/fonts/")              }              // Workaround for Android Gradle Plugin 3.4+ new asset directory              from(iconFontsDir) {                include(fontName)                into("merged_assets/${variant.name}/out/fonts/")              }            }        }        currentFontTask.dependsOn("merge${targetName}Resources")        currentFontTask.dependsOn("merge${targetName}Assets")        ["processArmeabi-v7a${targetName}Resources","processX86${targetName}Resources","processUniversal${targetName}Resources","process${targetName}Resources"        ].each { name ->            Task dependentTask = tasks.findByPath(name);            if (dependentTask != null) {                dependentTask.dependsOn(currentFontTask)            }        }    }}

Can you help me please)

Boost audio volume more than 100% in react native

$
0
0

My app is music player and some of the mp3's have lower volume. I want to Boost audio volume more than 100% in react native.

I have to tried this plugin:

  • react-native-volume-control
  • react-native-system-setting
  • react-native-audio-manager
  • react-native-sound

Version Mismatch in React-Native Version 0.60.3

$
0
0

"react": "16.8.6",

"react-native": "0.60.3"

React Native Version mismatch error after run new vesion app

enter image description here

How solve this issue in react native

$
0
0

$ npx react-native run-androidinfo Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.Jetifier found 864 file(s) to forward-jetify. Using 4 workers...info Starting JS server...info Launching emulator...error Failed to launch emulator. Reason: Could not start emulator within 30 seconds..warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.info Installing the app...

FAILURE: Build failed with an exception.

  • What went wrong:Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

  • 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.org

BUILD FAILED in 1m 23s

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

  • What went wrong:Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

  • 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.org

BUILD FAILED in 1m 23s

at checkExecSyncError (child_process.js:629:11)at execFileSync (child_process.js:647:13)at runOnAllDevices (E:\work\react-native\AwesomeProject1\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:39)

attach a file from a mobile app to an e-mail

$
0
0

In my mobile app, I need to figure out a way to take a file and attach it to an e-mail. This app shows it's possible - about half way down the page is their documentation to show users how (see section called "iOS & Android: Sending a file"). I looked up sending attachments using mailto and quickly found out that's not possible. This app is built using Expo, Vue Native and some React Native. How can this be achieved?

Viewing all 28469 articles
Browse latest View live


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