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

React Native Navigation and state management

$
0
0

React Navigation vs Routers(What should i use?)Redux vs Redux ToolKit(What should is use?)

What should i use for navigation between screens Reac† navigations or routers, And for state management inside the application what should be useful redux or redux tool?


TypeError: undefined is not an object (evaluating '(0,t(r(d[3])).default)().apiUrl' release channel android problem

$
0
0

I got this problem when i expo publish my react native app with or without --release-channel dev flag.I set up a config file environment.js to get different release version like this :

import Constants from "expo-constants";import { Platform } from "react-native";const localhost = Platform.OS === "ios" ? "localhost:8080" : "10.0.2.2:8080";const ENV = {  localhost: {    //apiUrl: localhost,    apiUrl: "http:xxxx",  },  dev: {    apiUrl: "http:xxxx",  },  staging: {    apiUrl: "http:xxxx",    // Add other keys you want here  },  prod: {    apiUrl: "http:xxxx",    // Add other keys you want here  },};const getEnvVars = (env = Constants.manifest.releaseChannel) => {  // What is __DEV__ ?  // This variable is set to true when react-native is running in Dev mode.  // __DEV__ is true when run locally, but false when published.  if (__DEV__ || env === undefined || env === null || env === "") {    return ENV.localhost;  } else if (env.indexOf("dev") !== -1) {    return ENV.dev;  } else if (env.indexOf("staging") !== -1) {    return ENV.staging;  } else if (env.indexOf("prod") !== -1) {    return ENV.prod;  }};export default getEnvVars;

I intercept the config with creation of new intance of axios like this :

import axios from "axios";import { getKey } from "./deviceStorage";import getEnvVars from "../../environment";const { apiUrl } = getEnvVars();const instance = axios.create({  // .. where we make our configurations  baseURL: apiUrl,});instance.interceptors.request.use((config) => {  const token = getKey("id_token");  token.then((value) => {    config.headers.Authorization = value ? `Bearer ${value}` : "";  });  return config;});export default instance;

when i emulate on my device everything work fine but when i expo publish and scan QR code with my device the app crash after splash screen and i got this error say :

enter image description here

So if i understand well the Constants.manifest.releaseChannel is undefined, any idea why this happen ? do i miss somthing on the import ?

When i put the Api URL directly on my axios interceptors everything work fine. import axios from "axios"; import { getKey } from "./deviceStorage";

//import getEnvVars from "../../environment";//const { apiUrl } = getEnvVars();const instance = axios.create({  // .. where we make our configurations  baseURL: "http://xxxx",});instance.interceptors.request.use((config) => {  const token = getKey("id_token");  token.then((value) => {    config.headers.Authorization = value ? `Bearer ${value}` : "";  });  return config;});export default instance;export const ApiUrls = {  authPatient: "/xxx",  authPractician: "/xxx",};

Thanks for help.

Reload AdMob Rewarded Ad without rebuilding App in React Native

$
0
0

I have created a Button to display a rewarded Ad whenever it gets clicked.There are two issues now:1. It takes too much time to load the Ad (I can click the button once or twice before anything happens).2. I want to reload the Ad right after it closes. It works but the App needs to restart.

AdMobRewardedComponent.js

  async componentDidMount() {  await setTestDeviceIDAsync("EMULATOR");  AdMobRewarded.setAdUnitID("ca-app-pub-3940256099942544/5224354917");  AdMobRewarded.addEventListener("rewardedVideoDidLoad", () => {  console.log("VideoLoaded")  });  AdMobRewarded.addEventListener("rewardedVideoDidFailToLoad", () =>  console.log("FailedToLoad")  );  AdMobRewarded.addEventListener("rewardedVideoDidOpen", () =>  console.log("Opened")  );  AdMobRewarded.addEventListener("rewardedVideoDidClose", () => {    loadAd(request.build());  console.log("Closed")  });  AdMobRewarded.addEventListener("rewardedVideoWillLeaveApplication", () =>  console.log("LeaveApp")  );  AdMobRewarded.addEventListener("rewardedVideoDidStart", () =>  console.log("Started")  );  AdMobRewarded.addEventListener("rewardedVideoDidRewardUser", () =>  console.log("Rewarded"),  );  await AdMobRewarded.requestAdAsync();}componentWillUnmount() {  AdMobRewarded.removeAllListeners();}_handlePress = async () => {  await AdMobRewarded.showAdAsync();};render() {  const { loadedAd } = this.state;  return (<TouchableButton onPress={this._handlePress} title="Coins erhalten!" image="adButton" status="active" style={styles.adButton}/>    );  }};

Is there a way to request a new Ad without restarting the whole App?Thanks for every answer!

how to navigate to specific screen after pressing rnfirebase notification

$
0
0

i'm using react native firebase and i'm getting notification whenever is needed, and these notifications have some data to navigate to specific screen.i used the firebase documentation to implement the functionality but it's not working as it's supposed to

Here is the document i've used Firebase & React-Navigationand my code looks something like this :

const Stack = createStackNavigator();const Router = () => {    const navigation = useNavigation();    const [loading, setLoading] = useState(true);    const [initialRoute, setInitialRoute] = useState('Splash');useEffect(() => {    //fcm    registerAppWithFCM();    // checkRNFBPermission();    const unsubscribe = messaging().onMessage(async remoteMessage => {        console.log('remote DATAAAAAAAAAAAAAAAAAAAAAAAA : ',remoteMessage.data);        // switch (remoteMessage.data.screen) {        //     case 'answer':{        //         console.log('inside switch condition 1 !!!!!!!!!!!!!');        //         useNavigation().navigate('Profile');        //         break;        //     }        //     case 'AnswerQuestion':{        //         console.log('inside switch condition 2 !!!!!!!!!!!!!');        //         useNavigation().navigate('Profile');        //         break;        //     }        //     default:        //         break;        // }        // Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));        // const owner = JSON.parse(remoteMessage.data.owner);        // const user = JSON.parse(remoteMessage.data.user);        // const picture = JSON.parse(remoteMessage.data.picture);    });    // Assume a message-notification contains a "type" property in the data payload of the screen to open   messaging().onNotificationOpenedApp(remoteMessage => {      console.log('Notification caused app to open from background state:',        remoteMessage.notification,      );      navigation.navigate('Profile');    });    //  Check whether an initial notification is available    messaging()    .getInitialNotification()    .then(remoteMessage => {      if (remoteMessage) {        console.log('Notification caused app to open from quit state:',          remoteMessage.data, //notification        );      }      setLoading(false);    });    messaging().setBackgroundMessageHandler(async remoteMessage => {        console.log('Message handled in the background!', remoteMessage);    });    return unsubscribe;    //fcm}, []);//fcmcheckRNFBPermission = async() => {    const enabled = await messaging().hasPermission();    if(enabled){        messaging()        .getToken()        .then(token => {            // console.log('deviceeeee fcm token ------> ', token);        });        }else{        requestUserPermission();    }}registerAppWithFCM = async() => {    await messaging().registerDeviceForRemoteMessages();}requestUserPermission = async() =>  {    const settings = await messaging().requestPermission();    if (settings) {        console.log('Permission settings:', settings);    }}//fcmrenderLoading = () => (<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'  }}><Text>Domanda</Text><ActivityIndicator size='large' color={colors.darkerTeal} /></View>);//firebaseif (loading) {    return null;}//firebasereturn(<Provider store={store}><PersistGate persistor={persistor} loading={this.renderLoading()}><Root><NavigationContainer><Stack.Navigator initialRouteName={initialRoute} headerMode="none"><Stack.Screen name="Splash" component={Splash} /><Stack.Screen name="Login" component={Login} /><Stack.Screen name="Main" component={Main} /><Stack.Screen name="AppIntro" component={AppIntro} /><Stack.Screen name="Tags" component={Tags} /><Stack.Screen name="Answers" component={Answers} /><Stack.Screen name="Profile" component={Profile} /><Stack.Screen name="EditInfo" component={EditInfo} /><Stack.Screen name="ChangePassword" component={ChangePassword} /><Stack.Screen name="AnswerQuestion" component={AnswerQuestion} /><Stack.Screen name="ContactUs" component={ContactUs} /></Stack.Navigator></NavigationContainer></Root></PersistGate></Provider>)};export default Router;

but when i add usenavigation and i want to use it it throws this error:Error: We couldn't find a navigation object. Is your component inside a screen in a navigator?

enter image description here

i can not use navigation.navigate('Profile'); to navigate to a specific screen.

java.lang.RuntimeException: Unable to instantiate application com.todos.MyApplication: java.lang.ClassNotFoundException

$
0
0
W/dalvikvm(21732): threadid=1: thread exiting with uncaught exception (group=0x41d0cda0)E/Drive.UninstallOperation( 1829): Package still installed com.todosE/AndroidRuntime(21732): FATAL EXCEPTION: mainE/AndroidRuntime(21732): Process: com.todos, PID: 21732E/AndroidRuntime(21732): java.lang.RuntimeException: Unable to instantiate application com.todos.MyApplication: java.lang.ClassNotFoundException: Didn't find class "com.todos.MyApplication" on path: DexPathList[[zip file "/data/app/com.todos-3.apk"],nativeLibraryDirectories=[/data/app-lib/com.todos-3, /vendor/lib, /system/lib]]E/AndroidRuntime(21732): at android.app.LoadedApk.makeApplication(LoadedApk.java:507)E/AndroidRuntime(21732): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4841)E/AndroidRuntime(21732): at android.app.ActivityThread.access$1600(ActivityThread.java:174)E/AndroidRuntime(21732): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1381)E/AndroidRuntime(21732): at android.os.Handler.dispatchMessage(Handler.java:102)E/AndroidRuntime(21732): at android.os.Looper.loop(Looper.java:146)E/AndroidRuntime(21732): at android.app.ActivityThread.main(ActivityThread.java:5731)E/AndroidRuntime(21732): at java.lang.reflect.Method.invokeNative(Native Method)E/AndroidRuntime(21732): at java.lang.reflect.Method.invoke(Method.java:515)E/AndroidRuntime(21732): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)E/AndroidRuntime(21732): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)E/AndroidRuntime(21732): at dalvik.system.NativeStart.main(Native Method)E/AndroidRuntime(21732): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.todos.MyApplication" on path: DexPathList[[zip file "/data/app/com.todos-3.apk"],nativeLibraryDirectories=[/data/app-lib/com.todos-3, /vendor/lib, /system/lib]]E/AndroidRuntime(21732): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)E/AndroidRuntime(21732): at java.lang.ClassLoader.loadClass(ClassLoader.java:497)E/AndroidRuntime(21732): at java.lang.ClassLoader.loadClass(ClassLoader.java:457)E/AndroidRuntime(21732): at android.app.Instrumentation.newApplication(Instrumentation.java:981)E/AndroidRuntime(21732): at android.app.LoadedApk.makeApplication(LoadedApk.java:502)E/AndroidRuntime(21732): ... 11 moreW/ActivityManager(  757):   Force finishing activity com.todos/.MainActivityW/DropBoxManagerService(  757): Dropping: data_app_crash (1781 > 0 bytes)

My AndroidManifest looks like the following...

<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/><uses-sdk      android:minSdkVersion="16"      android:targetSdkVersion="22" /><application    android:allowBackup="true"    android:label="@string/app_name"    android:icon="@mipmap/ic_launcher"    android:theme="@style/AppTheme"    android:name="com.todos.MyApplication"><meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/><activity      android:name=".MainActivity"      android:label="@string/app_name"      android:configChanges="keyboard|keyboardHidden|orientation|screenSize"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /></application>

This started breaking when I added com.todos.MyApplication source file...

enter image description here

When I open the project in Android Studio and navigate to MyApplication.java I see the following...

enter image description here

Enable/Disable firebase push notifications in react native app

$
0
0

I have a react app with settings screens which allows to disable all types of notifications. How to achieve this wasn't exactly clear in react native documentation. I can ask for user permission when he signup but how do I disable this permission from settings screen so he will not receive any notifications but user can enable them again in future.

I can do this using topics but that's pretty limited. I want to target using audience from firebase console. Any help appreciated.

Command failed: gradlew.bat installDebug

$
0
0

While developing an app I came into following error. I tried downgrading the java version from 11 to 8, but that wasn't helpful.

FAILURE: Build failed with an exception.* What went wrong:Could not create service of type ScriptPluginFactory using BuildScopeServices.createScriptPluginFactory().> Could not create service of type PluginResolutionStrategyInternal using BuildScopeServices.createPluginResolutionStrategy().* 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 15sCould 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/getting-started.htmlCommand failed: gradlew.bat installDebugError: Command failed: gradlew.bat installDebug    at checkExecSyncError (child_process.js:616:11)    at Object.execFileSync (child_process.js:634:13)    at runOnAllDevices (C:\Users\samie\Documents\React Native\auth\node_modules\react-native\local-cli\runAndroid\runAndroid.js:299:19)    at buildAndRun (C:\Users\samie\Documents\React Native\auth\node_modules\react-native\local-cli\runAndroid\runAndroid.js:135:12)    at isPackagerRunning.then.result (C:\Users\samie\Documents\React Native\auth\node_modules\react-native\local-cli\runAndroid\runAndroid.js:65:12)    at process._tickCallback (internal/process/next_tick.js:68:7)

React-Native production build works fine if downloaded directly from appcenter, but hangs on splash screen when it goes through the store

$
0
0

I have a beta build that auto-pushes from appcenter to the play console for the beta track. Everything is deployed and build numbers match. If I directly load the APK onto an android i don't have problems, but if i download the beta from the app store it hits the splash screen then hangs or crashes.


Google Play 64-bit requirement in React Native Version 0.61 release

$
0
0

I used to use version 0.54 of React Native, but due to a problem with the 64-bit version of Google, I had to create a new project (I did not update this version, but I created a new version).

I am currently using version 0.61.4 of React Native

After I got the aab output and wanted to publish it on Google Play, unfortunately I still had the same problem as before and I get the following error

This release is not compliant with the Google Play 64-bit requirement

The following APKs or App Bundles are available to 64-bit devices, but they only have 32-bit native code: 9.

Include 64-bit and 32-bit native code in your app. Use the Android App Bundle publishing format to automatically ensure that each device architecture receives only the native code it needs. This avoids increasing the overall size of your app

enter image description here

I put the gradle codes here for guidance

android/app/build.gradle

apply plugin: "com.android.application"import com.android.build.OutputFile/** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ *   // the name of the generated asset file containing your JS bundle *   bundleAssetName: "index.android.bundle", * *   // the entry file for bundle generation *   entryFile: "index.android.js", * *   // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format *   bundleCommand: "ram-bundle", * *   // whether to bundle JS and assets in debug mode *   bundleInDebug: false, * *   // whether to bundle JS and assets in release mode *   bundleInRelease: true, * *   // whether to bundle JS and assets in another build variant (if configured). *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants *   // The configuration property can be in the following formats *   //         'bundleIn${productFlavor}${buildType}' *   //         'bundleIn${buildType}' *   // bundleInFreeDebug: true, *   // bundleInPaidRelease: true, *   // bundleInBeta: true, * *   // whether to disable dev mode in custom build variants (by default only disabled in release) *   // for example: to disable dev mode in the staging build type (if configured) *   devDisabledInStaging: true, *   // The configuration property can be in the following formats *   //         'devDisabledIn${productFlavor}${buildType}' *   //         'devDisabledIn${buildType}' * *   // the root of your project, i.e. where "package.json" lives *   root: "../../", * *   // where to put the JS bundle asset in debug mode *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * *   // where to put the JS bundle asset in release mode *   jsBundleDirRelease: "$buildDir/intermediates/assets/release", * *   // where to put drawable resources / React Native assets, e.g. the ones you use via *   // require('./image.png')), in debug mode *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * *   // where to put drawable resources / React Native assets, e.g. the ones you use via *   // require('./image.png')), in release mode *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to *   // date; if you have any other folders that you want to ignore for performance reasons (gradle *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ *   // for example, you might want to remove it from here. *   inputExcludes: ["android/**", "ios/**"], * *   // override which node gets called and with what additional arguments *   nodeExecutableAndArgs: ["node"], * *   // supply additional arguments to the packager *   extraPackagerArgs: [] * ] */project.ext.react = [    entryFile: "index.js",    enableHermes: true,  // clean and rebuild if changing]apply from: "../../node_modules/react-native/react.gradle"/** * Set this to true to create two separate APKs instead of one: *   - An APK that only works on ARM devices *   - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */def enableSeparateBuildPerCPUArchitecture = false/** * Run Proguard to shrink the Java bytecode in release builds. */def enableProguardInReleaseBuilds = false/** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US.  Note that * this variant is about 6MiB larger per architecture than default. */def jscFlavor = 'org.webkit:android-jsc:+'/** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and mirrored here.  If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */def enableHermes = project.ext.react.get("enableHermes", false);android {    compileSdkVersion rootProject.ext.compileSdkVersion    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    defaultConfig {        applicationId "com.....android"        minSdkVersion rootProject.ext.minSdkVersion        targetSdkVersion rootProject.ext.targetSdkVersion        versionCode 34        versionName "3.0"        multiDexEnabled true    }    splits {        abi {            reset()            enable enableSeparateBuildPerCPUArchitecture            universalApk false  // If true, also generate a universal APK            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"        }    }    signingConfigs {        release {            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {                storeFile file(MYAPP_UPLOAD_STORE_FILE)                storePassword MYAPP_UPLOAD_STORE_PASSWORD                keyAlias MYAPP_UPLOAD_KEY_ALIAS                keyPassword MYAPP_UPLOAD_KEY_PASSWORD            }        }        debug {            storeFile file('debug.keystore')            storePassword 'android'            keyAlias 'androiddebugkey'            keyPassword 'android'        }    }    buildTypes {        debug {            signingConfig signingConfigs.debug        }        release {            // Caution! In production, you need to generate your own keystore file.            // see https://facebook.github.io/react-native/docs/signed-apk-android.            signingConfig signingConfigs.debug            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"            signingConfig signingConfigs.release        }    }    // applicationVariants are e.g. debug, release    applicationVariants.all { variant ->        variant.outputs.each { output ->            // For each separate APK per architecture, set a unique version code as described here:            // https://developer.android.com/studio/build/configure-apk-splits.html            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]            def abi = output.getFilter(OutputFile.ABI)            if (abi != null) {  // null for the universal-debug, universal-release variants                output.versionCodeOverride =                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode            }        }    }}dependencies {    implementation 'com.facebook.fresco:fresco:2.0.0'    implementation 'com.facebook.fresco:animated-gif:2.0.0'    implementation fileTree(dir: "libs", include: ["*.jar"])    implementation "com.facebook.react:react-native:+"  // From node_modules    //https://github.com/kmagiera/react-native-screens    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'    //https://github.com/react-native-community/react-native-maps/blob/master/docs/installation.md    implementation(project(':react-native-maps')){       exclude group: 'com.google.android.gms', module: 'play-services-base'       exclude group: 'com.google.android.gms', module: 'play-services-maps'    }    implementation 'com.google.android.gms:play-services-base:+'    implementation 'com.google.android.gms:play-services-maps:+'    if (enableHermes) {        def hermesPath = "../../node_modules/hermes-engine/android/";        debugImplementation files(hermesPath +"hermes-debug.aar")        releaseImplementation files(hermesPath +"hermes-release.aar")    } else {        implementation jscFlavor    }}// Run this once to be able to run the application with BUCK// puts all compile dependencies into folder libs for BUCK to usetask copyDownloadableDepsToLibs(type: Copy) {    from configurations.compile    into 'libs'}apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)// FIREBASE SDKs => https://invertase.io/oss/react-native-firebase/quick-start/android-firebase-credentialsapply plugin: 'com.google.gms.google-services'

android/gradle.properties

# Project-wide Gradle settings.# IDE (e.g. Android Studio) users:# Gradle settings configured through the IDE *will override*# any settings specified in this file.# For more details on how to configure your build environment visit# http://www.gradle.org/docs/current/userguide/build_environment.html# Specifies the JVM arguments used for the daemon process.# The setting is particularly useful for tweaking memory settings.# Default value: -Xmx10248m -XX:MaxPermSize=256m# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8# When configured, Gradle will run in incubating parallel mode.# This option should only be used with decoupled projects. More details, visit# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects# org.gradle.parallel=trueandroid.useAndroidX=trueandroid.enableJetifier=trueMYAPP_UPLOAD_STORE_FILE=key.jksMYAPP_UPLOAD_KEY_ALIAS=MY_KEY_ALIASMYAPP_UPLOAD_STORE_PASSWORD=******MYAPP_UPLOAD_KEY_PASSWORD=*****

android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.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.5.1')        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files        // FIREBASE SDKs => https://invertase.io/oss/react-native-firebase/quick-start/android-firebase-credentials        classpath 'com.google.gms:google-services:4.2.0'    }}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()        maven { url 'https://jitpack.io' }    }}

enter image description here

How to install react native app into my own smartphone device

$
0
0

I am currently learning mobile app development by using react native. I am using 'EXPO CLI' to simulate the code on my device/emulator. However, after reading the react-native official documentation, I realize that the steps required 'Android' folder in my project that does not exist because I did not run 'npm run eject'.

May I know is there any source on how to install my app into my device locally?(Meaning no longer running the app through EXPO).

Failed to find Build Tools revision 23.0.1

$
0
0

I am trying to build my first app with react-native.

I am following these 2 tutorial:

I am sure that I installed all the requirements from the second link but when I try running my app with react-native run-android, I get the following error:

Error

I executed this command while running genymotion.

This is all that I have installed in Android SDK:

enter image description here

enter image description here

I tried to install Android build tools 23.0.1 but I get this error:

enter image description here

What should I do?

react-native :app:installDebug FAILED

$
0
0

Install APK debug to my device failed.

jianglinghuadeMacBook-Pro:hello jianglinghua$ react-native run-androidJS server already running.Building and installing the app on the device (cd android && ./gradlew installDebug...WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.:app:preBuild UP-TO-DATE......:app:assembleDebug UP-TO-DATE:app:installDebugInstalling APK 'app-debug.apk' on 'MI NOTE LTE - 6.0.1'Unable to install /Users/jianglinghua/Desktop/hello/android/app/build/outputs/apk/app-debug.apkcom.android.ddmlib.InstallException: Failed to establish session    at com.android.ddmlib.Device.installPackages(Device.java:894)    ........    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61):app:installDebug FAILEDFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':app:installDebug'.> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to establish session* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.BUILD FAILEDTotal time: 13.945 secs

Could 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 have set up your Android development environment:https://facebook.github.io/react-native/docs/android-setup.html

I look at my devices

jianglinghuadeMacBook-Pro:hello jianglinghua$ adb devicesList of devices attached98333978    device

React Native fresh build error on compiling to android device

$
0
0

I recently build fresh app using react-native init.

After run react-native run-android I got this error:

FAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':app:preDexDebug'.> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_112\bin\java.exe'' finished with non-zero exit value 1* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.BUILD FAILEDTotal time: 19.52 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(node:3632) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'message' of undefined(node:3632) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I've already tried to run gradlew clean inside my android folder but still no luck.

Any solution?

React Native - TouchableOpacity not working inside an absolute positioned View

$
0
0

I've got an absolute positioned View that holds 3 TouchableOpacity components and the 3 fail to respond they are just not working at all, what is going wrong here please help me :)

Code

<View style={[styles.highNormalLowDocListHeaderStateContainer, {width: this.windowWidth, height: this.headerSmallHeight, position: 'absolute', left: 0, top: floatedHeaderTitleTop, elevation: 2}]}><TouchableOpacity onPress={() => this.getDocuments('high')} style={[styles.highNormalLowDocListHeaderStateTextContainer, highSelected.borderStyle]}><Text style={[styles.highNormalLowDocListHeaderStateText, highSelected.textStyle]}>HIGH</Text></TouchableOpacity><TouchableOpacity onPress={() => this.getDocuments('normal')} style={[styles.highNormalLowDocListHeaderStateTextContainer, normalSelected.borderStyle]}><Text style={[styles.highNormalLowDocListHeaderStateText, normalSelected.textStyle]}>NORMAL</Text></TouchableOpacity><TouchableOpacity onPress={() => this.getDocuments('low')} style={[styles.highNormalLowDocListHeaderStateTextContainer, lowSelected.borderStyle]}><Text style {[styles.highNormalLowDocListHeaderStateText, lowSelected.textStyle]}>LOW</Text></TouchableOpacity></View>

Screenshot

enter image description here

react-native-fs DocumentDirectoryPath Where is the catalog on the phone?

$
0
0

https://github.com/itinance/react-native-fs

import RNFS from 'react-native-fs';console.log(RNFS.DocumentDirectoryPath);// /data/data/a.a.a/filesRNFS.writeFile(  RNFS.DocumentDirectoryPath +'/test.txt','Lorem ipsum dolor sit amet','utf8',)  .then(success => console.log('FILE WRITTEN!'))  .catch(err => console.log(err.message));

But this file is not on the phone /Android/data/a.a.a/files/test.txt

Where is this file ?


Android: What is the best way of showing full page notification on incoming call without ConnectionService (React Native)

$
0
0

I'm unable to use ConnectionService because Twilio Video doesn't seem to support it. I've tried several alternatives but nothing seems to work very well so I'm interested in hearing what is the best suggestion. I have to handle the VOIP connection in the app so I want to show a custom UI on whether or not to pick up the incoming call and then direct to the app.

It seems like the doc's suggest https://developer.android.com/training/notify-user/time-sensitive IE

Intent fullScreenIntent = new Intent(this, CallActivity.class);PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,        fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

but I have two issues here

1) It seems to mostly show HeadsUp notifications2) If CallActivity.class does display and I create a UI here with answer / reject in this, I'm not able to navigate to the app afterwards if the screen is locked. The activity will close and i'll be presented with the lock screen.

Any thoughts or suggestions?

Note: I've tried to do the same general flow with ConnectionService (but because I can't use this) when I try to answer the call navigate to the app but I have the same issue with a locked screen where I am displayed the lock screen right after I accept the call

Images not appearing when running from APK

$
0
0

This issue relates to Android.

We have recently migrated our react-native project from Expo to bare workflow. We have an issue however whereby images are not loading when running the built apk file.

When debugging on an emulator or device using react-native android everything works fine. However on a built apk images simply do not appear.

Our build is being conducted as follows

react-native bundle --platform android /     --dev false /     --entry-file index.js      --bundle-output android/app/src/main/assets/app.bundle      --assets-dest android/app/src/main/resandroid/gradlew -p android cleanandroid/gradlew -p android assembleRelease

I can see that the first step bundles our images into the following directory

android/app/src/main/res/drawable-mdpi

Opening the built apk I can see that the images are referenced in the MANIFEST.MF file

apk/release/app-release/META-INF/services

like so

Name: res/drawable-mdpi-v4/app_assets_images_01.pngName: res/drawable-mdpi-v4/app_assets_images_02.png

and that the images do exist in the apk on that path.

So I am utterly confused as to why they do not display when running the apk on a device.

This is not an uncommon issue and there are several other Stack Overflow issues along this vein, however I have gone through all of them and none of the suggested solutions work for us.

Gradle version=5.6.3

RN version=61.5

React-native app is crashing without error in android studio

$
0
0

I am getting these errors ;

java.lang.RuntimeException: Unable to load script. Make sure you're either running a Metro server (run 'react-native start') or that your bundle 'index.android.bundle' is packaged correctly for release.

Getting error while running npm start in expo project

$
0
0

Couldn't start project on Android: Error running adb: adb: failed to install /home/spinny/.expo/android-apk-cache/Exponent-2.15.4.apk: Failure [INSTALL_PARSE_FAILED_NO_CERTIFICATES: Failed to collect certificates from /data/app/vmdl1162803835.tmp/base.apk using APK Signature Scheme v2: SHA-256 digest of contents did not verify]

This is the error i am getting while running npm start in project. I just created this project using expo but it shows this error.

Returning null is not an object React-native, "http request"

$
0
0

Hi i'm using Android device (no emulator) and I'm trying to get data form api with axios request but it return "null is not an object" even if I set state. I also can't retrieve data from IP address (localhost) I need to check de API version of my device and I don't know how to do that...I already try to change the "Android Manifest files but still giving me request network fail".. So Which android emulator allows http (localhost) request?? Thanks

This is my simple code:

import React from 'react';import { StyleSheet, View, Text, FlatList} from 'react-native';import axios from 'axios';class App extends React.Component {    state = {        url: 'https://raw.githubusercontent.com/Hardeepcoder/fake_json/master/Users',        users: null,    };async componentDidMount(){    const res = await axios.get(this.state.url);    this.setState({users: res.data['results']});}render () {return (<React.Fragment><View>{this.state.users.map(users => (<Text>{users.name}</Text>    ))}<Text>Welcome to bchef</Text><View><Text>Hola</Text></View></View></React.Fragment>);}};const styles = StyleSheet.create({});export default App;
Viewing all 28480 articles
Browse latest View live


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