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

Getting 'TypeError: undefined is not an object (evaluating 'view.getQuery)' when debugger is off

$
0
0

I get this error; 'TypeError: undefined is not an object (evaluating 'view.getQuery)'

I am able to use firebase.auth(). After I login the app I get the error.

Important Note: There is no error when debugger is on.

This is where I call firebase.database() which causes the error.

componentDidMount(){
    firebase.database().ref(`/posts/`).on('value', snapshot => {
        const keys = Object.keys(snapshot.val());
        alert(keys)
    });
}

I tried to upgrade and downgrade to all the firebase versions, it didn't solve.

related library versions;

"firebase": "^6.3.3",
"react": "^16.6.3",
"react-native": "0.58.3",
Android API 28
Java version: 1.8.0

Thanks for your recommendations.

Error screenshot: https://i.stack.imgur.com/oQT4W.png


Socket IO with React Native and Headless JS, can't kill it

$
0
0

This is mi first post so I will try to show my problem in a clear way and I'm not an android developer with a basic kownledge of java.

I'm trying to run a socket IO client in my react-native app, as I inquire in order to achieve this I use Headless JS task to have this socket running in the background and even when the app is close, the user recieves a notification.

I have all the flow working well, but the only problem is that when I execute Background.stopService(), the websocket do not disconect but the persistance notification disappear.

index.js (where I register the task)

const MyHeadlessTask = async () => {
  const email = await AsyncStorage.getItem('email');

  if (!!email) {
    try {
      let socket = SocketIOClient('url', {
        transports: ['websocket'],
        query: `email=${email}`
      });

      etc...
    } catch (ex) {
      console.log('[MyHeadlessTask() ex] ', ex)
    }
  }
};

AppRegistry.registerHeadlessTask('Background', () => MyHeadlessTask);

BackgroundEventService.java

public class BackgroundEventService extends HeadlessJsTaskService {
  @Nullable
  protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
    Bundle extras = intent.getExtras();
    WritableMap data = extras != null ? Arguments.fromBundle(extras) : Arguments.createMap();

    return new HeadlessJsTaskConfig(
      "Background",
      data,
      5000,
      true
    );
  }
}

BackgroundModule.java

public class BackgroundModule extends ReactContextBaseJavaModule {

  public static final String REACT_CLASS = "Background";
  private static ReactApplicationContext reactContext;

  public BackgroundModule(@Nonnull ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
  }

  @Nonnull
  @Override
  public String getName() {
    return REACT_CLASS;
  }

  @ReactMethod
  public void startService() {
    this.reactContext.startService(new Intent(this.reactContext, BackgroundService.class));
  }

  @ReactMethod
  public void stopService() {
    this.reactContext.stopService(new Intent(this.reactContext, BackgroundService.class));
  }
}

BackgroundPackage.java

public class BackgroundPackage implements ReactPackage {

  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    return Arrays.<NativeModule>asList(
      new BackgroundModule(reactContext)
    );
  }

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }
}

MainApplication.java (add package)

@Override
      protected List<ReactPackage> getPackages() {
        @SuppressWarnings("UnnecessaryLocalVariable")
        List<ReactPackage> packages = new PackageList(this).getPackages();
        // Packages that cannot be autolinked yet can be added manually here, for example:
        // packages.add(new MyReactNativePackage());
        packages.add(new BackgroundPackage());
        return packages;
      }

and this are the two ways that I writed BackgroundService.javafirst one

public class BackgroundService extends Service {

  private static final int SERVICE_NOTIFICATION_ID = 12345;
  private static final String CHANNEL_ID = "BACKGROUND";

  private Handler handler = new Handler();
  private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
      Context context = getApplicationContext();
      Intent myIntent = new Intent(context, BackgroundEventService.class);
      context.startService(myIntent);
      HeadlessJsTaskService.acquireWakeLockNow(context);
      //handler.postDelayed(this, 2000);
    }
  };
  private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      int importance = NotificationManager.IMPORTANCE_DEFAULT;
      NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "BACKGROUND", importance);
      channel.setDescription("CHANEL DESCRIPTION");
      NotificationManager notificationManager = getSystemService(NotificationManager.class);
      notificationManager.createNotificationChannel(channel);
    }
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    super.onCreate();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    this.handler.removeCallbacks(this.runnableCode);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    this.handler.post(this.runnableCode);
    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
      .setContentTitle("Safe Home")
      .setSmallIcon(R.mipmap.ic_launcher)
      .setContentIntent(contentIntent)
      .setOngoing(true)
      .setPriority(NotificationCompat.PRIORITY_MIN)
      .setVisibility(Notification.VISIBILITY_SECRET)
      .build();
    startForeground(SERVICE_NOTIFICATION_ID, notification);
    return START_STICKY;
  }

}

second one

public class BackgroundService extends Service {

  private static final int SERVICE_NOTIFICATION_ID = 12345;
  private static final String CHANNEL_ID = "BACKGROUND";
  private volatile boolean running = true;

  private Thread thread;
  private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
      if (running) {
        Context context = getApplicationContext();
        Intent myIntent = new Intent(context, BackgroundEventService.class);
        context.startService(myIntent);
        HeadlessJsTaskService.acquireWakeLockNow(context);
      } else {
        Context context = getApplicationContext();
        Intent myIntent = new Intent(context, BackgroundEventService.class);
        context.stopService(myIntent);
      }
    }
  };
  private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      int importance = NotificationManager.IMPORTANCE_DEFAULT;
      NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "BACKGROUND", importance);
      channel.setDescription("CHANEL DESCRIPTION");
      NotificationManager notificationManager = getSystemService(NotificationManager.class);
      notificationManager.createNotificationChannel(channel);
    }
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    super.onCreate();
  }

  @Override
  public void onDestroy() {
    running = false;
    this.thread.interrupt();
    super.onDestroy();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    this.thread = new Thread(this.runnableCode);
    this.thread.start();
    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
      .setContentTitle("Safe Home")
      .setSmallIcon(R.mipmap.ic_launcher)
      .setContentIntent(contentIntent)
      .setOngoing(true)
      .setPriority(NotificationCompat.PRIORITY_MIN)
      .setVisibility(Notification.VISIBILITY_SECRET)
      .build();
    startForeground(SERVICE_NOTIFICATION_ID, notification);
    return START_STICKY;
  }

}

This problem is giving me a headache, and I can't find a solution, I repeat everthing works well but it seems that the BackgroundEventService don't stop and the sockets still running, I try too many ways to stop the thread but nothing works for me. Maybe i'm using wrongs concepts or the is an error in my code...

transformClassesWithDexBuilderForDebug error at build

$
0
0

My React Native app was working yesterday.

I was working on a new version and wanted to push it to the Google Play Store. I tried fixing the library version for facebook and for react-native-fetch-blob.

I have been having this error for 6 hours now at build.

/Users/nicoara/Documents/GitHub/Parkour/node_modules/react-native-firebase/android/build/intermediates/intermediate-jars/debug/classes.jar: D8: Interface `com.google.android.gms.ads.reward.RewardedVideoAdListener` not found. It's needed to make sure desugaring of `io.invertase.firebase.admob.RNFirebaseAdMobRewardedVideo` is correct. Desugaring will assume that this interface has no default method.

> Task :app:transformClassesWithDexBuilderForDebug
com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /private/var/root/.gradle/caches/modules-2/files-2.1/org.robolectric/robolectric-utils/3.1.4/803d061ec7bd2ad78bcb74fb10caaeeb2dc4a74a/robolectric-utils-3.1.4.jar
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593)
        at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
        at java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:720)
        at com.android.ide.common.internal.WaitableExecutor.waitForTasksWithQuickFail(WaitableExecutor.java:146)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.transform(DexArchiveBuilderTransform.java:420)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:239)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:235)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
        at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:230)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
        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.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
        at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
        at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
        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.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
        at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:277)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:262)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
        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:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
        at java.lang.Thread.run(Thread.java:748)
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /private/var/root/.gradle/caches/modules-2/files-2.1/org.robolectric/robolectric-utils/3.1.4/803d061ec7bd2ad78bcb74fb10caaeeb2dc4a74a/robolectric-utils-3.1.4.jar
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:909)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.lambda$convertToDexArchive$6(DexArchiveBuilderTransform.java:834)
        at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
        at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
        at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
        at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
        at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing.
        at com.android.builder.dexing.D8DexArchiveBuilder.getExceptionToRethrow(D8DexArchiveBuilder.java:124)
        at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:101)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:904)
        ... 6 more
Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
        at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:70)
        at com.android.tools.r8.utils.ExceptionUtils.withD8CompilationHandler(ExceptionUtils.java:43)
        at com.android.tools.r8.D8.run(D8.java:94)
        at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:99)
        ... 7 more
Caused by: com.android.tools.r8.utils.AbortException: Error: MethodHandle.invoke and MethodHandle.invokeExact are only supported starting with Android O (--min-api 26)
        at com.android.tools.r8.utils.Reporter.failIfPendingErrors(Reporter.java:89)
        at com.android.tools.r8.utils.Reporter.fatalError(Reporter.java:60)
        at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:64)
        ... 10 more


> Task :app:transformClassesWithDexBuilderForDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /private/var/root/.gradle/caches/modules-2/files-2.1/org.robolectric/robolectric-utils/3.1.4/803d061ec7bd2ad78bcb74fb10caaeeb2dc4a74a/robolectric-utils-3.1.4.jar

Here is my environment:

Nicoaras-MBP:Parkour nicoara$ react-native info
info 
  React Native Environment Info:
    System:
      OS: macOS High Sierra 10.13.6
      CPU: (8) x64 Intel(R) Core(TM) i7-3615QM CPU @ 2.30GHz
      Memory: 41.30 MB / 8.00 GB
      Shell: 3.2.57 - /bin/bash
    Binaries:
      Node: 8.10.0 - /usr/local/bin/node
      Yarn: 1.5.1 - /usr/local/bin/yarn
      npm: 5.6.0 - /usr/local/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 11.4, macOS 10.13, tvOS 11.4, watchOS 4.3
      Android SDK:
        API Levels: 21, 23, 25, 26, 27, 28, 29
        Build Tools: 23.0.1, 25.0.1, 25.0.3, 26.0.2, 27.0.3, 28.0.3, 29.0.2
        System Images: android-25 | Google Play Intel x86 Atom, android-27 | Google Play Intel x86 Atom
    IDEs:
      Android Studio: 3.5 AI-191.8026.42.35.5977832
      Xcode: 9.4.1/9F2000 - /usr/bin/xcodebuild
    npmPackages:
      react: 16.8.5 => 16.8.5 
      react-native: 0.59.0 => 0.59.0 
    npmGlobalPackages:
      react-native-cli: 2.0.1
      react-native-create-library: 3.1.2

it might be because "react-native-fbsdk": "^0.7.0", so I attach the gradle:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 28
    buildToolsVersion "26.0.2"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 28
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    api "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    api 'com.facebook.react:react-native:+' // support react-native-v0.22-rc+
    api 'com.facebook.android:facebook-android-sdk:4.25.0'
}

repositories {
    mavenCentral()
    jcenter()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}

my package-json:

{
  "rnpm": {
    "assets": [
      "resources/fonts"
    ]
  },
  "name": "parkour",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "devtools": "react-devtools"
  },
  "dependencies": {
    "MyThumbnailLibrary": "file:./MyThumbnailLibrary",
    "firebase-functions": "^2.3.1",
    "moment": "^2.22.2",
    "node-pre-gyp": "^0.10.0",
    "react": "16.8.5",
    "react-native": "0.59.0",
    "react-native-app-intro-slider": "^0.2.4",
    "react-native-autolink": "^1.4.0",
    "react-native-contacts": "^3.1.2",
    "react-native-datepicker": "^1.7.2",
    "react-native-dialog": "^5.5.0",
    "react-native-emoji-selector": "^0.1.6",
    "react-native-fbsdk": "^0.7.0",
    "react-native-fetch-blob": "^0.10.8",
    "react-native-firebase": "5.3.0",
    "react-native-geocoding": "^0.3.0",
    "react-native-image-picker": "^0.26.10",
    "react-native-image-resizer": "^1.0.0",
    "react-native-image-zoom-viewer": "^2.2.12",
    "react-native-keyboard-aware-scroll-view": "^0.6.0",
    "react-native-localization": "^2.0.3",
    "react-native-maps": "^0.22.0",
    "react-native-navigation": "^1.1.440",
    "react-native-picker-select": "^4.4.0",
    "react-native-rate": "^1.1.6",
    "react-native-ux-cam": "^5.1.11",
    "react-native-vector-icons": "^4.6.0",
    "react-native-version-number": "^0.3.4",
    "react-native-video": "4.4.2",
    "react-native-video-processing": "^1.20.0",
    "react-redux": "^5.0.7",
    "redux": "^3.7.2"
  },
  "devDependencies": {
    "babel-jest": "22.2.0",
    "babel-preset-react-native": "5.0.2",
    "eslint-config-rallycoding": "^3.2.0",
    "jest": "24.1.0",
    "react-test-renderer": "16.8.3"
  },
  "jest": {
    "preset": "react-native"
  }
}

Customise tabs of native base

$
0
0

I need to customise tabs (change their background color ) from native base in my react native application, like shown in the image enter image description here

I've already tried this style={{ backgroundColor: '#C0C0C0' }} but i keep getting the default theme.

MaterialBottomTabs - Off-screen

$
0
0

I am developing an app with MaterialBottomTabs of React Navigation. When I test on Expo Client on Android, it works. But, when I build apk and install on device, the Tabs are off screen.

enter image description here

Expo CLI 3.9.0 environment info:

System:

  • OS: Linux 5.0 Ubuntu 19.04 (Disco Dingo)

  • Shell: 5.5.1 - /usr/bin/zsh

  • Binaries:

  • Node: 12.13.0 - /usr/bin/node

  • Yarn: 1.19.1 - /usr/bin/yarn

  • npm: 6.12.0 - /usr/bin/npm

  • npmPackages:

  • expo: ^35.0.0 => 35.0.0

  • react: 16.8.3 => 16.8.3

  • react-native:

  • https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz => 0.59.8

  • react-navigation: ^4.0.10 => 4.0.10

  • npmGlobalPackages:

  • expo-cli: 3.9.0

Can someone help me?

Thanks

Sorry for my bad English.

React Native : Expiring Daemon because JVM heap space is exhausted?

$
0
0

I just updated the Android Studio to 3.5.0 and I'm getting Expiring Daemon because JVM heap space is exhausted . Message while the build is running. Also, the build is taking more time to complete. Does anyone have any idea regarding this error help me?

Make the background blink for 1 second, whenever the state changes [duplicate]

$
0
0

I want the background of the view to be changed based on state , that comes from the API , I want the background of the view to be changed for 1 second whenever the state changes

Here is my code, This is what I tried to do

//*******************************************************

    async componentDidMount() {
    try {
      setInterval(async () => {
        const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');

        const blocks = await res.json();

               if(this.state.a!==blocks.id){ //comparing with initial state which is null
            this.setState({backgroundcolor:"#98fb98"})
        } //I want this to happen for 1 second whenever the state changes


        this.setState({
          panelone: dataPanelone,
          paneltwo: dataPaneltwo,
        })
      }, 2000);


    } catch(e) {
      console.log(e);
    }
   }

react native Fetch Network request failed on android

$
0
0

I'm trying to receive some simple json from mocky.

React native fetch function:

getMemberDomainList = async (name) => {
  try {
    let response = await fetch('https://5c9cc9ed3be4e30014a7d287.mockapi.io/api/domain', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    });
    let responseJson = await response.json();
    return responseJson;
  } catch (error) {
    console.error(error);
  }
}

I have tested the address in chrome on windows, it returns the expected mock data. But when the function is called on my android phone I get this error enter image description here

Error from remote debugger

...\node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:2348 TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:4337)
    at XMLHttpRequest.dispatchEvent (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10760)
    at XMLHttpRequest.setReadyState (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10511)
    at XMLHttpRequest.__didCompleteResponse (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10343)
    at ...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10449
    at RCTDeviceEventEmitter.emit (...\Libraries\Components\DrawerAndroid\DrawerLayoutAndroid.android.js:11)
    at MessageQueue.__callFunction (...\Libraries\ART\ReactNativeART.js:362)
    at blob:http://localhost:8081/79251787-d190-4650-8040-23d091c08738:2334
    at MessageQueue.__guard (...\Libraries\ART\ReactNativeART.js:312)
    at MessageQueue.callFunctionReturnFlushedQueue (...\Libraries\ART\ReactNativeART.js:139)

I'm also running a WebView in my app, which is pointing to a web url, it loads perfectly so I am sure that the phone has internet permission and access etc.


How to detect Ibeacons panic button in react-native?

$
0
0

I am using import Beacons from "react-native-beacons-manager"; for getting the data from Beacons to a device either ios/android.

Now my concern is is there any method which will handle is panic button pressed or not?

Value for title can not be cast from ReadablenativeMap to string

$
0
0
InsertDataToServer = () => {
const { pinValue1 } = this.state;
const { pinValue2 } = this.state;
const { pinValue3 } = this.state;
const { pinValue4 } = this.state;
var String_3 = pinValue1.concat("" , pinValue2);
var String_4 = String_3.concat("" ,  pinValue3);
var String_5 = String_4.concat("" ,  pinValue4);

fetch("http://www.aonde.biz/mobile/doLogin.php", {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    "pin":212,

  })
})
  .then(response => response.json())
  .then(responseJson => {
    // Showing response message coming from server after inserting records.
    Alert.alert(responseJson);
  })
  .catch(error => {
    console.error(error);
  });

In the above code when I pass pin parameter API then show this error. Thank youin image show full erro please give some idea how to resolve this issue.

toLowerCase on TextInput value is creating duplicate text if capital letter created

$
0
0

This one's an interesting one.

I created a TextInput that takes a value, then lower cases it, adds it to state, and sets it as the default value. On my android physical device, if you force a capital letter ( autocapitalize is set to none), and then quickly tap other letters, it will duplicate and add extra text.

Is there a way to avoid this?

Here's a snack https://snack.expo.io/Hk1reKHJ4

Run it on your android or on the simulator, tap the upper case button on the keyboard, tap a few other letters, tap the upper case again, tap a few other letters, and you should set this error.

Thanks!

export default class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      text: ''
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={ styles.inputContainer }
          defaultValue={ this.state.text }
          autoCapitalize="none"
          onChangeText={ value => this.setState({ 
            text: value.trim().toLowerCase()
            })}
        />
      </View>
    );
  }
}

React Native Facebook SDK Initialization on Android

$
0
0

I am integrating the Faecbook SDK into an existing react-native project and having the dreaded error: The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first.

I have followed the instructions carefully, so strings.xml contains:

<string name="facebook_app_id">xxxxx</string>

And in AndroidManifest.xml, inside the application element, I have

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

I've made the changes to settings.gradle and build.xml as described.

All the instructions say that I shouldn't need to call FacebookSdk.sdkInitialize() if I have done the above. I'm using react-native-fbsdk version 1.1.1 and react native 0.60.5

When I followed the instructions on a simple new react-native project it works, so I am wondering if it is a conflict with something in the app, but I'm not sure what to look for. Can anyone suggest how to debug?

Thanks.

React-Native :java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so

$
0
0

I have just updated my project to use react-native version 0.60.2 . But when I am trying to run an application on Android device it gets crashed after launch screen. I got the following error logs :

E/AndroidRuntime: FATAL EXCEPTION: create_react_context
    Process: com.tjspeed, PID: 3909
    java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so
        at com.facebook.soloader.SoLoader.doLoadLibraryBySoName(SoLoader.java:738)
        at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:591)
        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:529)
        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:484)
        at com.facebook.hermes.reactexecutor.HermesExecutor.<clinit>(HermesExecutor.java:20)
        at com.facebook.hermes.reactexecutor.HermesExecutorFactory.create(HermesExecutorFactory.java:27)
        at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:949)
        at java.lang.Thread.run(Thread.java:760)

Few suggestions available here : https://github.com/facebook/react-native/issues/25601 but unfortunately none of them worked for me. Please suggest the workaround.

react-native mapbox symbol layer render icons from URI dynamically

$
0
0

I need to show custom icons in my places, that icons are loaded from a specific URL dynamically. Here is my code.

const PlacesMarker = props => {
    const { places } = props
    const [geoJson, setGeoJson] = useState([])

    useEffect(() => {
        if (places)
            renderPlaces(places)
    }, [places])

    const renderPlaces = (places) => {
        let features = places.content.map((item) => {
            return {
                type: "Feature",
                id: item.id,
                properties: {
                    id: item.id,
                    icon: item.type.iconUri,
                    name: item.name,
                    type: item.type.name
                },
                geometry: {
                    type: "Point",
                    coordinates: [item.location.lon, item.location.lat],
                },
            }
        })
        setGeoJson(features)
    }

    return (
        <View>
            {geoJson.length > 0 ?
                <MapboxGL.ShapeSource id={'places-map'}
                    shape={{ type: "FeatureCollection", features: geoJson }}>
                    <MapboxGL.SymbolLayer
                        id={Math.random().toString()}
                        style={{
                            iconImage: ['get', 'icon']
                            iconAllowOverlap: true,
                            // iconSize: 0.80,
                            iconIgnorePlacement: true,
                            textField: ['get', 'icon']
                        }}
                    />
                </MapboxGL.ShapeSource> : null
            }
        </View >
    )
}

export default PlacesMarker

In the style, I used the expression 'get', and it works, because I set the textField with Icon URI value and it shows the uri. However if I set the iconImage property with the URI, then the icon appear successfully

Camera Module in "React Native" to display recently clicked image


React Native - initialProperties Android

$
0
0

I'm working under React-Native and I'm looking for passing initial props to JS via Java. This can be done easily in Objective-C with initialProperties like this :

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"myapp"
                                               initialProperties:initialProperties
                                                   launchOptions:launchOptions];

Where initialProperties is an NSDictionary which will be converted in JSON and available in JS via this.props. So I'm looking to do the same in Android. Any help ? Thanks

react-navigation Deep Linking opens app but not to correct page

$
0
0

Problem

I'm trying to setup Deep Linking and it doesn't open to the correct screen specified in my URL. The app opens but always to the current screen instead of the screen specified in the URL.

My app has the following navigation structure and I'm trying to navigate to the Notifications screen when the app opens

  1. Top level Switch Navigator
    1. SplashScreen
    2. AuthLoading Screen
    3. App (BottomTabNavigator)
      1. Home
      2. Profile
      3. Notifications
    4. Auth

What I've tried

I've tried setting up a new app and following their documentation and it works properly in the new project but I can't get it to work in my current project. I've also included redux in the new project to test the same environment.

I'm testing by running xcrun simctl openurl booted esportsdeeplink://app/notifications for iOS and adb shell am start -W -a android.intent.action.VIEW -d “esportsdeeplink://app/notifications” com.benji.esportscompetition for android.

Both have the same result of opening the app but not navigating to the specified page

Enviornment

  • react-native v0.60.4
  • react-navigation v3.11.1
  • redux v4.0.4
  • react-redux v7.1.0

Code I've tried to include all relevant code but cut down some imports and other code to try to be concise. I can post any additional code if you find it to be helpful

Index.js (entry point)

import App from './src/app/App';

const ReactNativeRedux = () => (
  <Provider store={store}>
    <PersistGate loading={<SplashScreen />} persistor={persistor}>
      <PushNotifications />
      <App />
    </PersistGate>
  </Provider>
);

AppRegistry.registerComponent(appName, () => ReactNativeRedux);

App.js

import AppContainer from './Components/BottomNavigation/NavigationRouting';

class App extends React.Component {
  render(props) {
    const prefix = 'esportsdeeplink://'
    console.log('prefix', prefix)
    return (
      <Fragment>
          <View style={{ flex: 1, backgroundColor }}>
          <StatusBar translucent backgroundColor="transparent" />
            <LoadingSpinner loading={this.props.loading} />
            <AppContainer
              ref={(navigatorRef) => {
                NavigationService.setTopLevelNavigator(navigatorRef);
              }}
              uriPrefix={prefix}
              screenProps={{
                http,
                saveFriendsFnUser: this.saveFriendsFnUser,
                signupComplete: this.signupComplete,
              }}
            />
          </View>
      </Fragment>
    );
  }
}

const mapStateToProps = (state) => ({
  loading: state.api.loading,
  user: state.user,
  math: state.math,
  response: state.response,
});

const mapDispatchToProps = (dispatch) => ({
  startupRequest: () => {
    dispatch(startupRequest());
  },
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(App);

NavigationRouting.js (where my navigators are created)

const BottomTabNav = createBottomTabNavigator(
  {
    Home: {
      screen: HomeScreen
    },
    Profile: {
      screen: ProfileStack
    },
    Notifications: {
      screen: Notifications,
      navigationOptions: () => ({
         tabBarVisible: false
       }),
      path: 'notifications',
    },

  },
  {
    tabBarComponent: CustomTabNav,
    initialRouteName: "Home"
  }
);

export default createAppContainer(
  createSwitchNavigator(
    {
      SplashScreen,
      AuthLoading: AuthLoadingScreen,
      App: {
        screen: BottomTabNav,
        path: 'app',
      },
      Auth: {
        screen: AuthStack,
        path: 'auth'
      }
    }
  )
);

Deep Linking Setup

iOS

iOS setup

projectFolder/ios/eSportsCompetition/AppDelegate.m

#import <React/RCTLinkingManager.h>

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

@end

Android

projectFolder/android/app/src/main/AndroidManifest.xml

<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="esportsdeeplink" />
        </intent-filter>
      </activity>

How to correctly trim user input in React Native?

$
0
0

I have TextInput that receives onChangeText as a prop:

<TextInput
  ...
  value={this.state.myString}
  onChangeText={this.updateInput.bind(this)}
/>

And updateInput is represented as:

updateInput(newString) {
  this.setState({ myString: newString.trim() });
}

This works for Android only. Is there some way to trim user input on both platforms (iOS, Android)?

Update

Actually, string is processed as trimmed, but you can still type as many whitespaces as you want on iOS. And if you type two whitespaces in a row the dot appears like it would be the end of the sentence. This is undesirable behaviour, is there a way to avoid it?

Link with example video: https://streamable.com/dzl3c

React-native : Execution failed for task ':app:compileDebugJavawithJavac'

$
0
0

I am relatively new to react-native and gradle (coding in general). I am trying to run my code on my phone but I keep getting the following error: Execution failed for task ':app:compileDebugJavawithJavac'.

I have tried looking for a solution but none of it worked. I have tried:

  1. reinstalling the environmental variable JAVA_HOME,

  2. ran gradlew clean, and

  3. also did npm install in my android folder but nothing worked.

Here is the response I've gotten:

C:\Users\Saint\OneDrive\Desktop\Important Stuff\Programming stuff\react\Calendar\android\app\src\main\java\com\Calendar\MainApplication.java:5: error: cannot find symbol
import com.facebook.react.ReactApplication;
                         ^

  symbol:   class ReactApplication 
  location: package com.facebook.react 
C:\Users\Saint\OneDrive\Desktop\Important Stuff\Programming stuff\react\Calendar\android\app\src\main\java\com\Calendar\MainApplication.java:6: error: cannot find symbol
import com.facebook.react.ReactNativeHost;
                         ^

  symbol:   class ReactNativeHost
  location: package com.facebook.react
C:\Users\Saint\OneDrive\Desktop\Important Stuff\Programming stuff\react\Calendar\android\app\src\main\java\com\Calendar\MainApplication.java:14: error: cannot find symbol
public class MainApplication extends Application implements ReactApplication {
                                                            ^

  symbol: class ReactApplication
C:\Users\Saint\OneDrive\Desktop\Important Stuff\Programming stuff\react\Calendar\android\app\src\main\java\com\Calendar\MainApplication.java:16: error: cannot find symbol
  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
                ^

  symbol:   class ReactNativeHost
  location: class MainApplication
C:\Users\Saint\OneDrive\Desktop\Important Stuff\Programming stuff\react\Calendar\android\app\src\main\java\com\Calendar\MainApplication.java:36: error: cannot find symbol
  public ReactNativeHost getReactNativeHost() 
         ^

  symbol:   class ReactNativeHost
  location: class MainApplication
C:\Users\Saint\OneDrive\Desktop\Important Stuff\Programming stuff\react\Calendar\android\app\src\main\java\com\Calendar\MainActivity.java:5: error: MainActivity is not abstract and does not override abstract method getPackages() in ReactActivity
public class MainActivity extends ReactActivity {
       ^

C:\Users\Saint\OneDrive\Desktop\Important Stuff\Programming stuff\react\Calendar\android\app\src\main\java\com\Calendar\MainApplication.java:16: error: cannot find symbol
  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
                                                       ^

  symbol:   class ReactNativeHost
  location: class MainApplication
C:\Users\Saint\OneDrive\Desktop\Important Stuff\Programming stuff\react\Calendar\android\app\src\main\java\com\Calendar\MainApplication.java:35: error: method does not override or implement a method from a supertype
  @Override
  ^

8 errors

FAILURE: Build failed with an exception.

 What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s
13 actionable tasks: 1 executed, 12 up-to-date
error 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/getting-started.html
error Command failed: gradlew.bat app:installDebug. Run CLI with --verbose flag for more details.

Thank you for your help!

EDIT: Here is my 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.3.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

Firebase signup with phone and email and then set password at first login

$
0
0

I have a mobile app with user signup by email and password working correctly. I want to change it as mentioned below.


I want to signup a user with his email and phone number without specifying the password. This is done by a system admin. Then at the first signing in, the user should be able to do a phone auth and then set the password. Do firebase support this? If yes, can someone point me out how to do it?

Viewing all 28474 articles
Browse latest View live


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