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

Using Typekit (Adobe) fonts on React Native project?

$
0
0

I recently opened some mobile app mockups that I have to develop. I'm using React Native (with Expo). The thing is, this mockups use a lot of Adobe fonts (Typekit).

I came across the doc: https://helpx.adobe.com/fonts/using/embed-codes.html, that can be used on web apps, not on compiled mobile apps.

I can't find any questions about it, but I wonder how mobile apps dev are implementing Typekit fonts in their projects?


React native navigation touches sometimes don't work

$
0
0

I'm hoping this is a known problem as I can't provide much to go on to get help solving it.

I'm using react native navigation for my app with the following setup:

  • AppContainer
    • Splash Screen
    • Setup Screen (A stack navigator)
    • Main screen (A stack navigator)

When my app starts it goes to the splash screen which decides if this is the first time running or not and depending on this decision calls this.props.navigation.navigate() with either main screen or setup screen.

So far this all works and is fairly standard.

When my app is launched for the first time the user is sent to the setup screen where they navigate through a series of screens entering data and selecting a next button to proceed to the next screen. This is where the problem occur. My first screen simply has some text and a next button (which is a regular button component) which when clicked calls this.props.navigation.push('nextviewname', {data: data}) to move to the next view.

The next view contains a textinput as well as back and next buttons which is where I'm having problems. When I reach this screen after freshly installing a release version of my app onto my Android X phone none of the inputs work. I can't:

  • Click next of back
  • Click the back arrow in the top left that is part of the header
  • Click the text input (the cursor does briefly show up in the text input but the keyboard never appears)
  • Click the hardware back key

On very rare occasions some of the above does work (e.g. the text input will sometimes work) and sometimes I'll even make it to the next step of my setup but it's rare that I make it all the way through

Weirdly this all works when I'm debugging my app on my phone.

Update: I've just tested on an Android 9 emulator and I'm getting the same issue

Has anyone seen/solved this issue before? At the moment it's effectively made my app useless.

Thanks for your help

my npx react-native run-android build fails

$
0
0

My colleague recently added react-native-camera to my project. I merged the code and when i run npx react-native run-android my build fails with:

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:preDebugBuild'.
> Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
   > Could not resolve project :react-native-camera.
     Required by:
         project :app
      > Cannot choose between the following variants of project :react-native-camera:
          - generalDebugRuntimeElements
          - mlkitDebugRuntimeElements
        All of them match the consumer attributes:
          - Variant 'generalDebugRuntimeElements' capability Rombot:react-native-camera:unspecified:
              - Unmatched attributes:
                  - Found com.android.build.api.attributes.VariantAttr 'generalDebug' but wasn't required.
                  - Found react-native-camera 'general' but wasn't required.
              - Compatible attributes:
                  - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
                  - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
                  - Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.
          - Variant 'mlkitDebugRuntimeElements' capability Rombot:react-native-camera:unspecified:
              - Unmatched attributes:
                  - Found com.android.build.api.attributes.VariantAttr 'mlkitDebug' but wasn't required.
                  - Found react-native-camera 'mlkit' but wasn't required.
              - Compatible attributes:
                  - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
                  - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
                  - Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.

I have tried to remove my node modules and then do a npm install but i still get the same error. Any help would be great. Thanks in advance.

Firebase crashlytics doesn't work for Android

$
0
0

I have integrated firebase analytics and crashlytics into react-native application.The analytics part works fine.

But Crashlytics doesn't work for android, see attachment below.enter image description here

For IOS at least it shows something on firebase console.enter image description here

Here is what I see in adb logcat for android.

Caused by: java.lang.RuntimeException: Background thread crash
01-06 14:21:47.949 15169 20465 E AndroidRuntime:    at com.crashlytics.android.core.CrashTest.throwRuntimeException(CrashTest.java:21)
01-06 14:21:47.949 15169 20465 E AndroidRuntime:    at com.crashlytics.android.core.CrashTest$1.doInBackground(CrashTest.java:50)
01-06 14:21:47.949 15169 20465 E AndroidRuntime:    at com.crashlytics.android.core.CrashTest$1.doInBackground(CrashTest.java:42)
01-06 14:21:47.949 15169 20465 E AndroidRuntime:    at android.os.AsyncTask$3.call(AsyncTask.java:378)
01-06 14:21:47.949 15169 20465 E AndroidRuntime:    at java.util.concurrent.FutureTask.run(FutureTask.java:266)

I have tried every other solution on stackoverflow but didn't help

android/app/build.gradle

apply plugin: "com.android.application"
apply plugin: "io.fabric"


import com.android.build.OutputFile
project.ext.react = [
        entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    defaultConfig {
        applicationId "*.*.*"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 48
        versionName "6.3.15"
        multiDexEnabled true
        ndk {
            abiFilters 'armeabi-v7a','arm64-v8a','x86','x86_64'
        }
        lintOptions {
            checkReleaseBuilds false
            abortOnError false
        }
        missingDimensionStrategy 'react-native-camera', 'general'

    }
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include 'armeabi-v7a','arm64-v8a','x86','x86_64'
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // 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:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            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 project(':@react-native-firebase_crashlytics')
    implementation project(':@react-native-firebase_app')
    implementation project(':@react-native-firebase_analytics')
    implementation project(':react-native-network-info')
    implementation project(':react-native-camera')    
    implementation project(':trace-network')
    implementation project(':react-native-wmsso')
    implementation project(':rn-fetch-blob')
    implementation project(':react-native-webview')
    implementation project(':react-native-video')
    implementation project(':react-native-haptic-feedback')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-device-info')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  
}
buildscript {
    repositories {
        google()
        maven {
            url 'https://maven.google.com'
        }
        maven { url 'https://maven.fabric.io/public' }
        jcenter()




    dependencies {

        classpath 'com.google.gms:google-services:4.2.0'

    }


}



task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}



buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }

}


apply plugin: 'com.google.gms.google-services'

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 = 19
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()

        maven { url 'https://maven.fabric.io/public' }

    dependencies {
        classpath("com.android.tools.build:gradle:3.4.0")
        classpath 'com.google.gms:google-services:4.3.3'
        classpath 'io.fabric.tools:gradle:1.31.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        maven {
            url 'https://maven.google.com'
        }

        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

Firebase Performance Monitoring React Native integration

$
0
0

I have install Firebase Performance monitoring on my React Native app and integrate it successfully. After i want to track my network requests performance and go through as documentation.

const trackRequest = async (url,method) => {
    // Define the network metric
    const metric = await perf().newHttpMetric(url, method);

    // Define meta details
    metric.putAttribute('testAttr', 'testValue');

    // Perform a HTTP request and provide response information
    const response = await fetch(url);
    metric.setHttpResponseCode(response.status);
    metric.setResponseContentType(response.headers.get('Content-Type'));
    metric.setResponsePayloadSize(response.headers.get('Content-Length'));

    // Stop the trace
    await metric.stop();

    return response.json();
};

I use this function from documentation and call it every network requests time

fetch("www.example.com")
trackRequest("www.example.com","GET")

Can anyone explain me what i were doing wrong ?

com.facebook.react.bridge.WritableMap.copy() on a null object reference

$
0
0

I have a background service on my app wrote with react-native. When start service then closed app and alert: "Stoped: Unfortunately". I open project on android studio for test and debug. and i take it problem.

My react-native version: 0.0.1 and my package json like that;


{
  "name": "kimdeyizApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "lint": "eslint",
    "postinstall": "npx jetify"
  },
  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.2",
    "react-native-axios": "^0.17.1",
    "react-native-elements": "^1.2.6",
    "react-native-push-notification": "^3.1.9",
    "react-native-router-flux": "^4.0.6",
    "react-redux": "^7.0.3",
    "redux": "^4.0.1",
    "redux-actions": "^2.6.5",
    "socket.io-client": "^2.3.0",
    "watchman": "^1.0.0"
  },
  "devDependencies": {
    "@babel/core": "7.6.4",
    "@babel/runtime": "7.6.3",
    "@react-native-community/eslint-config": "0.0.3",
    "babel-jest": "24.9.0",
    "eslint": "6.5.1",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-plugin-import": "^2.17.2",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-react": "^7.13.0",
    "jest": "24.9.0",
    "jetifier": "^1.6.4",
    "metro-react-native-babel-preset": "0.51.1",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

HeadlessJsTaskConfig.java

package com.facebook.react.jstasks;
import com.facebook.react.bridge.WritableMap;
public class HeadlessJsTaskConfig {
  private final String mTaskKey;
  private final WritableMap mData;
  private final long mTimeout;
  private final boolean mAllowedInForeground;
  private final HeadlessJsTaskRetryPolicy mRetryPolicy;
  public HeadlessJsTaskConfig(String taskKey, WritableMap data) {
    this(taskKey, data, 0, false);
  }
  public HeadlessJsTaskConfig(String taskKey, WritableMap data, long timeout){
    this(taskKey, data, timeout, false);
  }
  public HeadlessJsTaskConfig(
      String taskKey, WritableMap data, long timeout, boolean allowedInForeground) {
    this(taskKey, data, timeout, allowedInForeground, NoRetryPolicy.INSTANCE);
  }
  public HeadlessJsTaskConfig(
      String taskKey,
      WritableMap data,
      long timeout,
      boolean allowedInForeground,
      HeadlessJsTaskRetryPolicy retryPolicy) {
    mTaskKey = taskKey;
    mData = data;
    mTimeout = timeout;
    mAllowedInForeground = allowedInForeground;
    mRetryPolicy = retryPolicy;
  }

  public HeadlessJsTaskConfig(HeadlessJsTaskConfig source) {
    mTaskKey = source.mTaskKey;
    mData = source.mData.copy();
    mTimeout = source.mTimeout;
    mAllowedInForeground = source.mAllowedInForeground;

    final HeadlessJsTaskRetryPolicy retryPolicy = source.mRetryPolicy;
    if (retryPolicy != null) {
      mRetryPolicy = retryPolicy.copy();
    } else {
      mRetryPolicy = null;
    }
  }

  String getTaskKey() {
    return mTaskKey;
  }

  WritableMap getData() {
    return mData;
  }

  long getTimeout() {
    return mTimeout;
  }

  boolean isAllowedInForeground() {
    return mAllowedInForeground;
  }

   HeadlessJsTaskRetryPolicy getRetryPolicy() {
    return mRetryPolicy;
  }

}

and my error;

  --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.kimdeyizapp, PID: 8514
    java.lang.NullPointerException: Attempt to invoke interface method 'com.facebook.react.bridge.WritableMap com.facebook.react.bridge.WritableMap.copy()' on a null object reference
        at com.facebook.react.jstasks.HeadlessJsTaskConfig.<init>(HeadlessJsTaskConfig.java:88)
        at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:106)
        at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:84)
        at com.facebook.react.HeadlessJsTaskService$2.run(HeadlessJsTaskService.java:123)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 8514 SIG: 9
Process 8514 terminated.

So other a problem is like that.

E/cr_VariationsUtils: Failed reading seed file "/data/user/0/com.kimdeyizapp/app_webview/variations_seed": /data/user/0/com.kimdeyizapp/app_webview/variations_seed (No such file or directory)

Thanks for helps.

React-native 0.61.2 with hermes disassembling index.android.bundle

$
0
0

I created a release build of my app with react-native 0.61.2 and enabled Hermes. In my Crashlytics I receive information about crashes along with stacktraces. Perviously I used to apply apktool to extract index.android.bundle from my apk, and it contained js code where I was able to find the issue by stacktrace.

But now using Hermes index.android.bundle seems to contain bytecode rather than js and I wasted a day trying to disassemble it. The last thing I tried was hbcdump tool mentioned in https://github.com/facebook/hermes/blob/master/doc/BuildingAndRunning.md, but all I get is "Error: fail to deserializing bytecode: Wrong bytecode version. Expected 73 but got 62"

What should I do to disassemble index.android.bundle created with Hermes? Any help is highly appreciated!

react-native-camera (android): takePictureAsync() throws error

$
0
0

After calling takePictureAsync() from react-native-camera, i'm getting this error:

{
  "framesToPop": 1,
  "nativeStackAndroid": [],
  "userInfo": null,
  "message": "Preview is paused - resume it before taking a picture.",
  "code": "E_TAKE_PICTURE_FAILED",
  "line": 2131,
  "column": 45,
  "sourceURL": "http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false"
}

So I tried using resumePreview() method before calling takePictureAsync() and now I'm getting a different error message:

{
  "framesToPop": 1,
  "nativeStackAndroid": [],
  "userInfo": null,
  "message": "takePicture failed",
  "code": "E_TAKE_PICTURE_FAILED",
  "line": 2131,
  "column": 45,
  "sourceURL": "http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false"
}

My component and usage i identical to that of https://react-native-community.github.io/react-native-camera/docs/rncamera

<RNCamera
      ref={ref => {
        this.camera = ref;
      }}
      style={styles.preview}
      type={RNCamera.Constants.Type.back}
      flashMode={RNCamera.Constants.FlashMode.on}
      androidCameraPermissionOptions={{
        title: 'Permission to use camera',
        message: 'We need your permission to use your camera',
        buttonPositive: 'Ok',
        buttonNegative: 'Cancel',
      }}
      androidRecordAudioPermissionOptions={{
        title: 'Permission to use audio recording',
        message: 'We need your permission to use your audio',
        buttonPositive: 'Ok',
        buttonNegative: 'Cancel',
      }}
      onGoogleVisionBarcodesDetected={({ barcodes }) => {
        console.log(barcodes);
      }}
    />




takePicture = async () => {
    if (this.camera) {
      const options = { quality: 0.5, base64: true };
      try {
        this.camera.resumePreview();
        const data = await this.camera.takePictureAsync(options);
        console.log(data.uri);
      } catch (error) {
        console.log(JSON.stringify(error, null, 2));
      }
    }
  };

versions:

"react-native": "0.61.2",
"react-native-camera": "git+https://git@github.com/react-native-community/react-native-camera.git",

Works fine on iOS. Is this an issue with the library or my implementation?


Code injection to hide Website parts in WebView not working

$
0
0

Hi I made a Flutter webview app but the notification of cookies (first image) does not hide when I injected this code:

(await _controller.future).evaluateJavascript("document.getElementById('st_notification_1')[0].style.display='none';");

enter image description here

The code of one of my pages which I should Inject the two code is this:

import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  WebViewController _myController;
      final Completer<WebViewController> _controller =
      Completer<WebViewController>();
  @override
  Widget build(BuildContext context) {
    return SafeArea(
            child: Scaffold(
                  body: WebView(
                  initialUrl: 'https://syncshop.online/en/',
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (controller) {
                  _controller.complete(controller);
                },
          onPageFinished: (controller) async {
          (await _controller.future).evaluateJavascript("document.getElementsByClassName('footer-container')[0].style.display='none';"); //THIS ONE WORKS 
          (await _controller.future).evaluateJavascript("document.getElementById('st_notification_1')[0].style.display='none';");
          (await _controller.future).evaluateJavascript("document.getElementById('sidebar_box')[0].style.display='none';");
          },
          ),
    floatingActionButton: FutureBuilder<WebViewController>(
        future: _controller.future,
        builder: (BuildContext context, AsyncSnapshot<WebViewController> controller) {
          if (controller.hasData) {
            return FloatingActionButton(
            onPressed: () {
              controller.data.reload();
            },
            child: Icon(Icons.refresh),
          );
          }
          return Container();
        }
        ),
          ),
      );
    }
}

React-native gradle.groovy cannot be found

$
0
0

I'm fairly new to react-native. Recently I ejected the expo kit as I needed to generate an APK file to try on multiple phones. but I'm currently facing a problem as when I try building the project using Android Studio I end up getting the following error:

(Basically for some reason gradle.groovy is not there anymore.) Should I have made ant changes to the project before ejecting and opting for a bare react project?

org.gradle.api.GradleScriptException: A problem occurred evaluating settings 'android'.
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
    at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:206)
    at org.gradle.configuration.DefaultScriptTarget.addConfiguration(DefaultScriptTarget.java:74)
    at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:211)
    at org.gradle.configuration.BuildOperationScriptPlugin$1$1.run(BuildOperationScriptPlugin.java:69)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.configuration.BuildOperationScriptPlugin$1.execute(BuildOperationScriptPlugin.java:66)
    at org.gradle.configuration.BuildOperationScriptPlugin$1.execute(BuildOperationScriptPlugin.java:63)
    at org.gradle.configuration.internal.DefaultUserCodeApplicationContext.apply(DefaultUserCodeApplicationContext.java:48)
    at org.gradle.configuration.BuildOperationScriptPlugin.apply(BuildOperationScriptPlugin.java:63)
    at org.gradle.initialization.ScriptEvaluatingSettingsProcessor.applySettingsScript(ScriptEvaluatingSettingsProcessor.java:67)
    at org.gradle.initialization.ScriptEvaluatingSettingsProcessor.process(ScriptEvaluatingSettingsProcessor.java:58)
    at org.gradle.initialization.PropertiesLoadingSettingsProcessor.process(PropertiesLoadingSettingsProcessor.java:37)
    at org.gradle.initialization.SettingsEvaluatedCallbackFiringSettingsProcessor.process(SettingsEvaluatedCallbackFiringSettingsProcessor.java:34)
    at org.gradle.initialization.RootBuildCacheControllerSettingsProcessor.process(RootBuildCacheControllerSettingsProcessor.java:36)
    at org.gradle.initialization.BuildOperationSettingsProcessor$2.call(BuildOperationSettingsProcessor.java:48)
    at org.gradle.initialization.BuildOperationSettingsProcessor$2.call(BuildOperationSettingsProcessor.java:45)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:314)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:304)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:100)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.initialization.BuildOperationSettingsProcessor.process(BuildOperationSettingsProcessor.java:45)
    at org.gradle.initialization.DefaultSettingsLoader.findSettingsAndLoadIfAppropriate(DefaultSettingsLoader.java:109)
    at org.gradle.initialization.DefaultSettingsLoader.findAndLoadSettings(DefaultSettingsLoader.java:48)
    at org.gradle.initialization.SettingsAttachingSettingsLoader.findAndLoadSettings(SettingsAttachingSettingsLoader.java:31)
    at org.gradle.internal.composite.CommandLineIncludedBuildSettingsLoader.findAndLoadSettings(CommandLineIncludedBuildSettingsLoader.java:34)
    at org.gradle.internal.composite.ChildBuildRegisteringSettingsLoader.findAndLoadSettings(ChildBuildRegisteringSettingsLoader.java:47)
    at org.gradle.internal.composite.CompositeBuildSettingsLoader.findAndLoadSettings(CompositeBuildSettingsLoader.java:35)
    at org.gradle.initialization.DefaultGradleLauncher$LoadBuild.run(DefaultGradleLauncher.java:249)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.initialization.DefaultGradleLauncher.loadSettings(DefaultGradleLauncher.java:174)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:137)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:124)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:154)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:55)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:50)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:45)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:47)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:44)
    at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:79)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:44)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:81)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.UncheckedIOException: Could not read script 'C:\Users\Abdul\Desktop\release\Frontend\node_modules\react-native-unimodules\gradle.groovy' as it does not exist.
    at org.gradle.groovy.scripts.internal.DefaultScriptSourceHasher.hash(DefaultScriptSourceHasher.java:48)
    at org.gradle.groovy.scripts.internal.CrossBuildInMemoryCachingScriptClassCache.getOrCompile(CrossBuildInMemoryCachingScriptClassCache.java:45)
    at org.gradle.groovy.scripts.internal.BuildScopeInMemoryCachingScriptClassCompiler.compile(BuildScopeInMemoryCachingScriptClassCompiler.java:50)
    at org.gradle.groovy.scripts.DefaultScriptCompilerFactory$ScriptCompilerImpl.compile(DefaultScriptCompilerFactory.java:50)
    at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:179)
    at org.gradle.configuration.BuildOperationScriptPlugin$1$1.run(BuildOperationScriptPlugin.java:69)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.configuration.BuildOperationScriptPlugin$1.execute(BuildOperationScriptPlugin.java:66)
    at org.gradle.configuration.BuildOperationScriptPlugin$1.execute(BuildOperationScriptPlugin.java:63)
    at org.gradle.configuration.internal.DefaultUserCodeApplicationContext.apply(DefaultUserCodeApplicationContext.java:48)
    at org.gradle.configuration.BuildOperationScriptPlugin.apply(BuildOperationScriptPlugin.java:63)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyScript(DefaultObjectConfigurationAction.java:109)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$000(DefaultObjectConfigurationAction.java:38)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$1.run(DefaultObjectConfigurationAction.java:68)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:143)
    at org.gradle.groovy.scripts.DefaultScript.apply(DefaultScript.java:134)
    at org.gradle.api.Script$apply.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:157)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:169)
    at settings_7w2qyhvg9px62igpvf3gw03uf.run(C:\Users\Abdul\Desktop\release\Frontend\android\settings.gradle:1)
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
    ... 110 more
Caused by: java.io.FileNotFoundException: C:\Users\Abdul\Desktop\release\Frontend\node_modules\react-native-unimodules\gradle.groovy (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at org.gradle.internal.hash.DefaultFileHasher.hash(DefaultFileHasher.java:38)
    at org.gradle.api.internal.changedetection.state.CachingFileHasher.snapshot(CachingFileHasher.java:89)
    at org.gradle.api.internal.changedetection.state.CachingFileHasher.snapshot(CachingFileHasher.java:72)
    at org.gradle.api.internal.changedetection.state.CachingFileHasher.hash(CachingFileHasher.java:57)
    at org.gradle.groovy.scripts.internal.DefaultScriptSourceHasher.hash(DefaultScriptSourceHasher.java:45)
    ... 135 more

font-family "ionicons" is not a system font and has not been loaded through Font.loadAsync

$
0
0

I am using native-base UI framework for react-native. I am having same error again and again even I'm not using 'Ionicons' anywhere in my project. I tried to delete node_modules and running npm install but it didn't work.
I also tried example solution given by native-base team, on github here. And also solution by Expo on Using custion fonts - Expo. enter image description here But nothing worked for me.

How to implement Google Campaign Measurement of google analytics in react native android?

$
0
0

How can I implement Google Campaign Measurement using react native . I use google analytics using react-native-firebase package.

I am trying to follow this guide: https://developers.google.com/analytics/devguides/collection/android/v4/campaigns

Steps I am taking

  1. Add the Google Analytics receiver to your AndroidManifest.xml file
<application>
    <!-- Used for Google Play Store Campaign Measurement-->
    <receiver android:name="com.google.android.gms.analytics.CampaignTrackingReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>
    <service android:name="com.google.android.gms.analytics.CampaignTrackingService"
        android:enabled="true"
        android:exported="false" />
</application>
  1. Broadcasting an INSTALL_REFERRER Intent
$ cd <path_to_adb_tool>
$ echo 'am broadcast \
    -a com.android.vending.INSTALL_REFERRER \
    -n "your.package.name/path.to.receiver" \
    --es "referrer" \
      "utm_source=test_source&utm_medium=test_medium&utm_term=test_term&utm_content=test_content&utm_campaign=test_name"; \
    exit' | ./adb shell
  1. Verifying the Campaign Data Was Received- not able to receive this below line in adb output GAv4 : Received installation campaign: source=testSource

Is there any extra step I need to do for react native with react-native-firebase?

React native version mismatch: native version: 0.61.5, javascript version: 0.57.7

$
0
0

I have a react-native app, which does not use expo. I get the following error:

 React Native version mismatch.
                             │ 
                             │ JavaScript version: 0.57.7
                             │ Native version: 0.61.5
                             │ 
                             └ Make sure that you have rebuilt the native code. If the problem persists try clearing the Watchman and packager caches with `watchman watch-del-all && react-native start --reset-cache`.

I have done everything mentioned in this question and nothing has worked so far.

I have updated react-native version to 0.61.5 . It is installed and it is also mentioned in package.json. I have also updated all packages in packages.json.

The project also uses react-navigation. In @react-navigation file in node modules, in native/package.json file, it is the only place that "react-native": "^0.57.7", is mentioned under devDependencies. I have installed the latest react-navigation, 4.0.10.

React Native: custom header not set to header navigation

$
0
0

I created top navigator in my android react native project :

const topSurvayorsNavigator = createMaterialTopTabNavigator({
    ActiveSurveyor: {
        screen: MomayezanScreen,
        params: { status: 1 },
        navigationOptions: {
            tabBarLabel: <Text style={{ fontSize: 12, fontFamily: 'IranianSans' }}>ممیزان فعال</Text>,
            tabBarIcon: (tabInfo => {
                return (
                    <Icon name="stars" size={15} color={tabInfo.tintColor} />
                );
            })
        },
    },
    DeActiveSurveyor: {
        screen: MomayezanScreen,
        params: { status: 0 },
        navigationOptions: {
            tabBarLabel: <Text style={{ fontSize: 12, fontFamily: 'IranianSans' }}>ممیزان غیرفعال</Text>,
            tabBarIcon: (tabInfo => {
                return (
                    <Icon name="md-stars" size={15} color={tabInfo.tintColor} />
                );
            })
        },

    }
}, {
    swipeEnabled: true,
    tabBarOptions: {
        labelStyle: {
            fontSize: 12
        },
        activeTintColor: Colors.darkGray
    }
});

After that i added topSurvayorsNavigator to main stack navigator :

const AuditMomayezanNavigator = createStackNavigator({
    Dashboard: DashboardScreen,
    ListSurveyor: {
        screen: topSurvayorsNavigator,
    },
    Detail: SurveyorDetailsScreen,
}, {
    defaultNavigationOptions: defaultNavOptions
});

and finally :

export default createAppContainer(AuditMomayezanNavigator);

In MomayezanScreen according params i loaded different data on flatlist. In page i want to set custom header so i do this:

MomayezanScreen.navigationOptions = ({ navigation }) => {
    const statusId = navigation.getParam('status');
    console.log(statusId);
    return {
        header: () => <CustomHeader
            title={`ممیزان ${statusId === 0 ? 'غیر فعال' : 'فعال'}`} />
    }
} 

But unfortunately nothing is changed and header did not have any title.

enter image description here

Actually coustom header is not set in header component!!! What is your idea?

I changed MomayezanScreen.navigationOptions to this:

MomayezanScreen.navigationOptions = ({ navigation }) => {
    const statusId = navigation.getParam('status');
    console.log(statusId);
    return {
        headerTitle: `test`
    }
}

But still nothing is printed on header.

React-navigation touches sometimes don't work

$
0
0

I'm hoping this is a known problem as I can't provide much to go on to get help solving it.

I'm using react-navigation for my app with the following setup:

  • AppContainer
    • Splash Screen
    • Setup Screen (A stack navigator)
    • Main screen (A stack navigator)

When my app starts it goes to the splash screen which decides if this is the first time running or not and depending on this decision calls this.props.navigation.navigate() with either main screen or setup screen.

So far this all works and is fairly standard.

When my app is launched for the first time the user is sent to the setup screen where they navigate through a series of screens entering data and selecting a next button to proceed to the next screen. This is where the problem occur. My first screen simply has some text and a next button (which is a regular button component) which when clicked calls this.props.navigation.push('nextviewname', {data: data}) to move to the next view.

The next view contains a textinput as well as back and next buttons which is where I'm having problems. When I reach this screen after freshly installing a release version of my app onto my Android X phone none of the inputs work. I can't:

  • Click next of back
  • Click the back arrow in the top left that is part of the header
  • Click the text input (the cursor does briefly show up in the text input but the keyboard never appears)
  • Click the hardware back key

On very rare occasions some of the above does work (e.g. the text input will sometimes work) and sometimes I'll even make it to the next step of my setup but it's rare that I make it all the way through

Weirdly this all works when I'm debugging my app on my phone.

Update: I've just tested on an Android 9 emulator and I'm getting the same issue.

Update 2: This is getting weird, when the app is in a broken state I can still bring up the react native debug menu however when I click Toggle Inspector nothing happens (i.e. I don't get the inspector UI). It's looking like this is somehow breaking everything.

Has anyone seen/solved this issue before? At the moment it's effectively made my app useless.

Update 3: Some code to hopefully make things clearer:

const SetupUser = createStackNavigator(
  {
    SetupUser: WelcomeScreen,
    SetupName: UserName,
    SetupCurrentWeight: CurrentWeight,
    SetupGoalWeight: GoalWeight,
    SetupGoalDate: GoalDate,
    Summary: Summary,
    LogWeight: LogWeight,
  },
  {
    defaultNavigationOptions: {
      headerStyle: {
        backgroundColor: '#001830',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    },
  },
);

const MainApp = createStackNavigator(
  {
    LogWeight: LogWeight,
    LogWeightSummary: LogWeightSummary,
  },
  {
    defaultNavigationOptions: {
      headerStyle: {
        backgroundColor: '#001830',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    },
  },
);

export default createAppContainer(
  createSwitchNavigator(
    {
      MainApp: MainApp,
      SplashScreen: SplashScreen,
      SetupUser: SetupUser,
    },
    {
      initialRouteName: 'SplashScreen',
    },
  ),
);

In getting this code snippit together (I've removed the tab navigator as the error is still there even without it) I think I've managed to track down the source of the issue however I'm still not sure how to fix it. The first view loaded is the splash screen which looks like this:

export default class SplashScreen extends React.Component {
constructor(props) {
    super(props);

    GoBinder.verifyDatabase()
      .then(GoBinder.getLastUser())
      .then(user => {
        this.props.navigation.navigate(
          user.user == null ? 'SetupUser' : 'MainApp',
        );
      })
      .catch(error => {
        GoBinder.toast('Error while checking initial user state: ' + error);
      });
  }
render() {
    return (
      <View style={styles.container}>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}

In the above code, GoBinder.verifyDatabase() and GoBinder.getLastUser() are calls to native code which perform some database operation to get things setup and check to see if there are any existing users. I believe the issue is this.props.navigation.navigate is firing too quickly which is causing react-navigation to load the next screen but get messed up in the process.

I've tried following the suggestions in this post https://www.novemberfive.co/blog/react-performance-navigation-animations about moving blocking code into InteractionManager.runAfterInteractions under componentDidMount however this made no difference. However, it I manually trigger the move to the new screen using a button everything works correctly so its really looking like the act of programatically changing screens is messing things up.

Thanks for your help


ETIMEDOUT and HOSTROUTE error in TCP socket over a WiFi with no internet in React Native Android application

$
0
0

I'm working on a react-native IoT application which requires me to connect to local device over hotspot and provide it with WiFi credentials.

I'm trying it in 3 phones: Vevo1601(android 6), Asus Zenfone Z00LD(android 6.1) and Redmi Note 5 (android 8.1)

Connecting to hotspot works seamless but TCP socket throws errors 8/10 times in Vevo, 2/10 times in Asus and 5/10 times in Redmi.

I'm using react-native TCP library by peel technologies : https://www.npmjs.com/package/react-native-tcp

let ip = "";
let port = "1884";
ip = this.generateDeviceIP(sortedWifiDevice.BSSID);
wifi.forceWifiUsage(true); //method in self created android library to    bind socket to wifi network
var net = require("react-native-tcp");
let tcpClient = net.createConnection({ host: ip, port: port }

Android method forceWifiUsage

public void forceWifiUsage(boolean useWifi) {
    boolean canWriteFlag = false;
    if (useWifi) {
        Log.d("> Wifi Logs >> ", "usewifi is true : ");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Log.d("> Wifi Logs >> ", "build >M line 1327 ");
                canWriteFlag = Settings.System.canWrite(context);

                if (!canWriteFlag) {
                    Log.d("> Wifi Logs >> ", "build >M .... !canwrite 1331 ");
                    Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                    intent.setData(Uri.parse("package:" + context.getPackageName()));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            }

            if (((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && canWriteFlag) ||
                    ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) &&
                            !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M))) {
                Log.d("> Wifi Logs >> ", "build >M .... canwrite 1342 ");
                final ConnectivityManager manager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkRequest.Builder builder;
                builder = new NetworkRequest.Builder();
                //set the transport type do WIFI
                builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);


                manager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(Network network) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            manager.bindProcessToNetwork(network);
                            Log.d("> Wifi Logs >> ", "bindprocess 1356");
                        } else {
                            //This method was deprecated in API level 23
                            ConnectivityManager.setProcessDefaultNetwork(network);
                            Log.d("> Wifi Logs >> ", "setprocess default network 1360");
                        }
                        try {
                        } catch (Exception e) {
                            Log.d("> Wifi Logs >> ", "exception 1364");
                            e.printStackTrace();
                        }
                        manager.unregisterNetworkCallback(this);
                        Log.d("> Wifi Logs >> ", "unregisternetwork 1368");
                    }
                });
            }
        }
    } else {
        Log.d("> Wifi Logs >> ", "usewifi false");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Log.d("> Wifi Logs >> ", "usewifi false..... greater than marshmallow... 1376");
            ConnectivityManager manager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            manager.bindProcessToNetwork(null);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Log.d("> Wifi Logs >> ", "usewifi false..... greater than lollipop....1381");
            ConnectivityManager.setProcessDefaultNetwork(null);
        }
    }
}

I have tried everything from the android official docs to stuff on this portal but it just throwing ETIMEDOUT or Host unreachable most of the times but then sometimes it works.

I don't even have a sim card in Vevo phone and only a working over WiFi connection.

how to send the push-up notification to the user that are nearest to a user location in react-native

$
0
0

I am developing an android app using React-native , in which a user post a problem. Now i want to send notification only to those mechanics who are nearest to the user current location. I have register the mechanic shop location based on which i want to send the notification. I am using firebase cloud database.

How to use mock location in React Native - Android

$
0
0

I'm trying to write react native module for changing GPS location in android studio. I'm setting permission and set application name in mock location developer settings. After that also, its not working and also not getting any error. These is my sample code,

    @ReactMethod
    private Context mContext;
    public void mockLocation(String gps, Callback callback) {
        LocationManager mLocationManager = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
          mLocationManager.removeTestProvider(LocationManager.GPS_PROVIDER);
          mLocationManager.addTestProvider
                  (
                          LocationManager.GPS_PROVIDER,
                          "requiresNetwork" == "",
                          "requiresSatellite" == "",
                          "requiresCell" == "",
                          "hasMonetaryCost" == "",
                          "supportsAltitude" == "",
                          "supportsSpeed" == "",
                          "supportsBearing" == "",

                          android.location.Criteria.POWER_LOW,
                          android.location.Criteria.ACCURACY_FINE
                  );

          Location newLocation = new Location(LocationManager.GPS_PROVIDER);

          newLocation.setLatitude (22.5726);
          newLocation.setLongitude(88.3639);

          newLocation.setAccuracy(500);

          mLocationManager.setTestProviderEnabled
                  (
                          LocationManager.GPS_PROVIDER,
                          true
                  );

          mLocationManager.setTestProviderStatus
                  (
                          LocationManager.GPS_PROVIDER,
                          LocationProvider.AVAILABLE,
                          null,
                          System.currentTimeMillis()
                  );

          mLocationManager.setTestProviderLocation
                  (
                          LocationManager.GPS_PROVIDER,
                          newLocation
                  );
        callback.invoke("Location changed");
      } 

And my react code is,

componentDidMount() {
    RNNativeToastLibrary.mockLocation("gps", (res) => {
      console.log(res)
    });
  }

React native bottom tab bar pushing itself up when opening keyboard

$
0
0

We are using createBottomTabNavigator. In one of the tab contains search bar at the top. While clicking on that search bar, we are opening the keyboard. But the keyboard pushing up the bottom tab bar also. We need the bottom tab bar remains at the bottom when opening keyboard.

  1. One of the solution I have tried is, in android manifest, I have changed android:windowSoftInputMode="adjustPan" or "adjustNothing". It is working fine as expected. But we are using chat layout in another tab which needs "adjustResize". So I have to keep "adjustResize" for windowSoftInputMode.
  2. As another solution, I tried to change windowSoftInputMode inside component itself. SO I have tried with this - https://www.npmjs.com/package/react-native-android-keyboard-adjust. But no use.
  3. As another one, I tried to create a TabBarComponent like mentioned here https://github.com/react-navigation/react-navigation/issues/618. But not working as expected.
const SignedIn = createBottomTabNavigator(
  {
    Followers: {
      screen: FollowerStack,
      ...
    },
    Search: {
      screen: SearchStack,
    },
    Home: {
      screen: HomeStack,
    },
    Bookmarks: {
      screen: BookmarkStack,
    },
    Profile: {
      screen: ProfileStack,
    }
  },
  {
    initialRouteName: "Home",
    tabBarPosition: 'bottom',
    swipeEnabled: false,
    animationEnabled: false,
    tabBarOptions: {
      keyboardHidesTabBar: true,
      showIcon: true,
      showLabel: false,
      activeTintColor: "red",
      inactiveTintColor: "gray",
      adaptive: true,
      safeAreaInset: {
        bottom: "always"
      },
      style: {
        position: 'relative',
        backgroundColor: "#F9F8FB",
        height: TAB_NAVIGATOR_DYNAMIC_HEIGHT,
        paddingTop: DeviceInfo.hasNotch() ? "5%" : "0%",
        minHeight: TAB_NAVIGATOR_DYNAMIC_HEIGHT,
        width: '100%',
        bottom: 0
      }
    }
  }
);
  1. Is there any other properties existed for making the bottom tab bar sticky at the bottom? or
  2. Is it possible to change the android manifest windowSoftInputMode from inside component? Please comment below if you required any other code part for reference. Thanks for any help.

React Native can't find native method

$
0
0

I am new in React Native, here is my problem: I want to start an activity by calling NATIVE code from REACT NATIVE on a button click.

I am getting an error, says on the JS console 'cannot read property \'startActivity\'of undefined.

  ...MORE CODE...
  import ActivityStarter from './ActivityStarter'
  ...MORE CODE...

                <Button
            onPress={() => ActivityStarter.startActivity()}
            title='Login'  />

on the Java end:

public class ActivityStarterModule extends ReactContextBaseJavaModule {

public ActivityStarterModule(ReactApplicationContext reactContext) {
    super(reactContext);
}

@Override
public String getName() {
    return "ActivityStarter";
}

@ReactMethod
public void startActivity() {
    ReactApplicationContext context = getReactApplicationContext();
    Intent intent = new Intent(context, DashBoardScreen.class);
    context.startActivity(intent);
}}
Viewing all 29785 articles
Browse latest View live


Latest Images

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