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

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.


Not receiving notifications from Firebase in Android, but connection is established

$
0
0

Versions

  • @react-native-firebase/app: 6.3.4
  • @react-native-firebase/messaging: 6.3.4
  • react: 16.9.0
  • react-native: 0.61.4

Inside my App.js file, I'm registering for notifications like this

...
import messaging from '@react-native-firebase/messaging';

const App: () => React$Node = () => {
  const registerForNotifications = async () => {
    const granted = await messaging().requestPermission();
    if (granted) {
      console.log('User granted messaging permissions!');
    } else {
      console.log('User declined messaging permissions :(');
    }
    await messaging().registerForRemoteNotifications();

    const unsubscribe = messaging().onMessage(async remoteMessage => {
      console.log('FCM Message Data:', remoteMessage.data);
    });
    const token = await messaging().getToken();
    console.log({token});
    return unsubscribe;
  };

  useEffect(() => {
    SplashScreen.hide();
    registerForNotifications();
  }, []);

  ...
}

and it shows me that user granted messaging permissions, and it seems to register correctly for remote notifications, and finally I get the token, which seems to be ok and connected.

In firebase messaging console, I send a new notification and in possible targets it seems to be my user (Inside Cloud messaging menu)

enter image description here

So I do not see any error, but for some reason I sent multiple notifications, and I don't receive them, it doesn't matter if the app is open or close. I don't know what to do because I cannot see any error.

android.security.KeyStoreException: Signature/MAC verification failed When trying to decrypt in a React Native Module

$
0
0

I am facing a weird issue which has started to happen after a recent Android Update on my Galaxy S8 phone.

I have a React Native Module for encrypting values using a key stored in Android KeyStore in which was working perfectly fine and suddenly started to fail with the following exception during decryption:

android.security.KeyStoreException: Signature/MAC verification failed

I did a bit of investigation and figured out that if I call my decrypt method instantly after encrypting a value, it works fine but if I try to do the decryption in another call from the JS side, it fails.

Also if I prompt the user for biometrics, the decryption works fine regardless of being the same call or another call.

Here is my module code:

public class BiometricsModule extends ReactContextBaseJavaModule {

    private Promise _promise;
    private ReactApplicationContext _context;
    private String CIPHER_IV = "CIPHER_IV";
    private SettingsStore settingsStore;

    public FVBiometricsModule(@NonNull ReactApplicationContext reactContext) {
        super(reactContext);
        _context = reactContext;
        settingsStore = new SettingsStore(_context);
    }

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

    @ReactMethod
    public void isEnrolledAsync(final Promise promise) {
        _promise = promise;

        try {
            WritableMap resultData = new WritableNativeMap();

            Integer biometricsCheckResult =  BiometricManager.from(_context).canAuthenticate();
            String reason = parseResult(biometricsCheckResult);

            resultData.putBoolean("result", reason == "SUCCESS");
            if (reason != "SUCCESS") {
                resultData.putString("reason", reason);
            }
            promise.resolve(resultData);
        } catch (Exception e) {
            promise.reject(e);
        }

    }

    @ReactMethod
    public void promptForBiometricsAsync(String prompt, String title, String cancelButtonText, final Promise promise) {
        _promise = promise;
        prompt(null, null, prompt, title, cancelButtonText, false, null);
    }

    @ReactMethod
    public void setPasswordAsync(String username, String password, Boolean biometricsProtected, String prompt, String title, String cancelButtonText, final Promise promise) {
        _promise = promise;
        try {
            generateKey(biometricsProtected);
            Cipher cipher = getCipher(biometricsProtected);
            SecretKey secretKey = getSecretKey();
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            settingsStore.setValue(CIPHER_IV, Base64.encodeToString(cipher.getIV(), Base64.DEFAULT));
            if (biometricsProtected) {
                prompt(username, password, prompt, title, cancelButtonText, false, cipher);
            } else {
                encrypt(username, password, cipher);
            }
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void getPasswordAsync(String username, Boolean biometricsProtected, String prompt, String title, String cancelButtonText, final Promise promise) {
        _promise = promise;
        try {
            Cipher cipher = getCipher(biometricsProtected);
            SecretKey secretKey = getSecretKey();
            byte[] _iv = Base64.decode(settingsStore.getValue(CIPHER_IV, null), Base64.DEFAULT);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, biometricsProtected ? new IvParameterSpec(_iv) : new GCMParameterSpec(128, _iv));
            if (biometricsProtected) {
                prompt(username, null, prompt, title, cancelButtonText, true, cipher);
            } else {
                decrypt(username, cipher);
            }
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    private String parseResult(Integer biometricsCheckResult) {
        String result = "SUCCESS";
        switch (biometricsCheckResult) {
            case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
                result = "NOT_AVAILABLE";
                break;
            case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
                result = "NOT_AVAILABLE";
                break;
            case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
                result = "NOT_ENROLLED";
                break;
        }
        return result;
    }

    private void generateKey(Boolean biometricsProtected) {
        generateSecretKey(new KeyGenParameterSpec.Builder(
                _context.getPackageName(),
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(biometricsProtected ? KeyProperties.BLOCK_MODE_CBC : KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(biometricsProtected ? KeyProperties.ENCRYPTION_PADDING_PKCS7 : KeyProperties.ENCRYPTION_PADDING_NONE)
                .setUserAuthenticationRequired(biometricsProtected)
                .setInvalidatedByBiometricEnrollment(biometricsProtected)
                .build());
    }

    private void generateSecretKey(KeyGenParameterSpec keyGenParameterSpec) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            keyGenerator.init(keyGenParameterSpec);
            keyGenerator.generateKey();
        } catch (Exception e) {
            _promise.reject(e);
        }
    }

    private SecretKey getSecretKey() {
        try {
            KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
            keyStore.load(null);
            return ((SecretKey)keyStore.getKey(_context.getPackageName(), null));
        } catch (Exception e) {
            _promise.reject(e);
            return null;
        }
    }

    private Cipher getCipher(Boolean biometricsProtected) {
        try {
            return Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                    + (biometricsProtected ? KeyProperties.BLOCK_MODE_CBC : KeyProperties.BLOCK_MODE_GCM) + "/"
                    + (biometricsProtected ? KeyProperties.ENCRYPTION_PADDING_PKCS7 : KeyProperties.ENCRYPTION_PADDING_NONE));
        } catch (Exception e) {
            _promise.reject(e);
            return null;
        }
    }

    private void prompt(String username, String password, String prompt, String title, String cancelBButtonText, Boolean decrypt, Cipher cipher) {
        MainActivity.mainActivity.runOnUiThread(new Runnable() {
            public void run() {
                WritableMap resultData = new WritableNativeMap();
                Executor _executor = ContextCompat.getMainExecutor(MainActivity.mainActivity);

                BiometricPrompt _biometricPrompt = new BiometricPrompt(MainActivity.mainActivity,
                        _executor, new BiometricPrompt.AuthenticationCallback() {
                    @Override
                    public void onAuthenticationError(int errorCode,
                                                      @NonNull CharSequence errString) {
                        super.onAuthenticationError(errorCode, errString);
                        try {
                            resultData.putBoolean("result", false);
                            _promise.resolve(resultData);
                        } catch (Exception e) {
                            _promise.reject(e);
                        }
                    }

                    @Override
                    public void onAuthenticationSucceeded(
                            @NonNull BiometricPrompt.AuthenticationResult result) {
                        super.onAuthenticationSucceeded(result);
                        try {
                            if (password != null && !decrypt) {
                                byte[] encryptedInfo = result.getCryptoObject().getCipher().doFinal(password.getBytes(Charset.defaultCharset()));
                                settingsStore.setValue(username, Base64.encodeToString(encryptedInfo, Base64.DEFAULT));
                                resultData.putBoolean("result", true);
                            } else if (decrypt) {
                                String decryptedInfo = new String(result.getCryptoObject().getCipher().doFinal(Base64.decode(settingsStore.getValue(username, null), Base64.DEFAULT)));
                                resultData.putString("password", decryptedInfo);
                            }
                            _promise.resolve(resultData);
                        } catch (Exception e) {
                            _promise.reject(e);
                        }
                    }

                    @Override
                    public void onAuthenticationFailed() {
                        super.onAuthenticationFailed();
                        try {
                            resultData.putBoolean("result", false);
                            _promise.resolve(resultData);
                        } catch (Exception e) {
                            _promise.reject(e);
                        }
                    }
                });

                BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()
                        .setTitle(title)
                        .setSubtitle(prompt)
                        .setNegativeButtonText(cancelBButtonText)
                        .setConfirmationRequired(false)
                        .build();

                if (cipher != null)
                    _biometricPrompt.authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher));
                else
                    _biometricPrompt.authenticate(promptInfo);
            }
        });
    }

    private void encrypt(String username, String password, Cipher cipher) {
        try {
            WritableMap resultData = new WritableNativeMap();
            byte[] encryptedInfo = cipher.doFinal(password.getBytes(Charset.defaultCharset()));
            settingsStore.setValue(username, Base64.encodeToString(encryptedInfo, Base64.DEFAULT));
            resultData.putBoolean("result", true);
            _promise.resolve(resultData);
        } catch (Exception e) {
            _promise.reject(e);
        }
    }

    private void decrypt(String username, Cipher cipher) {
        try {
            WritableMap resultData = new WritableNativeMap();
            String decryptedInfo = new String(cipher.doFinal(Base64.decode(settingsStore.getValue(username, null), Base64.DEFAULT)));
            resultData.putString("password", decryptedInfo);
            _promise.resolve(resultData);
        } catch (Exception e) {
            _promise.reject(e);
        }
    }
}

At some point I though it is because of the conversion between byte[] and string but that's not the issue.

Building React Native app fails: Task :app:generateDebugBuildConfig FAILED

$
0
0

I am trying to run an app on an Android emulator. I followed the instructions in the React Native docs for installing Android Studio and setting the environment variables. I can create a default project with '''npx react-native init''' and run it without problems, so I guess my installation is fine. I cloned the repository, "npm installed" and got the following errors, trying to build fails as well. Since I am completely new to React Native and did not participate on this project so far I am clueless on how to approach this.

PS C:\Users\PP\pp-app> npm install
npm WARN aws-amplify-react-native@2.2.3 requires a peer of graphql@0.13.0 but none is installed. You must install peer dependencies yourself.
npm WARN aws-amplify-react-native@2.2.3 requires a peer of react-native-fs@^2.12.1 but none is installed. You must install peer dependencies yourself.
npm WARN aws-amplify-react-native@2.2.3 requires a peer of react-native-sound@^0.10.9 but none is installed. You must install peer dependencies yourself.
npm WARN aws-amplify-react-native@2.2.3 requires a peer of react-native-voice@^0.2.6 but none is installed. You must install peer dependencies yourself.
npm WARN eslint-plugin-react@7.12.4 requires a peer of eslint@^3.0.0 || ^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN eslint-plugin-react-native@3.6.0 requires a peer of eslint@^3.17.0 || ^4 || ^5 but none is installed. You must install peer dependencies yourself.
npm WARN react-native-elements@0.19.1 requires a peer of react-native-vector-icons@^4.2.0 but none is installed. You must install peer dependencies yourself.
npm WARN react-native-qrcode-scanner@1.2.3 requires a peer of react-native-camera@^1.0.2 but none is installed. You must install peer dependencies yourself.

audited 953593 packages in 10.847s
found 40843 vulnerabilities (39913 low, 930 moderate)
  run `npm audit fix` to fix them, or `npm audit` for details
PS C:\Users\PP\pp-app> npx react-native run-android
error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:
  - amazon-cognito-identity-js (to unlink run: "react-native unlink amazon-cognito-identity-js")
  - react-native-camera (to unlink run: "react-native unlink react-native-camera")
  - react-native-linear-gradient (to unlink run: "react-native unlink react-native-linear-gradient")
  - react-native-vector-icons (to unlink run: "react-native unlink react-native-vector-icons")
  - react-native-webview (to unlink run: "react-native unlink react-native-webview")
This is likely happening when upgrading React Native from below 0.60 to 0.60 or above. Going forward, you can unlink this dependency via "react-native unlink <dependency>" and it will be included in your 
app automatically. If a library isn't compatible with autolinking, disregard this message and notify the library maintainers.
Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 1054 file(s) to forward-jetify. Using 8 workers...
info Starting JS server...
info Installing the app...
Downloading https://services.gradle.org/distributions/gradle-4.10.1-all.zip
...............................................................................................................

Welcome to Gradle 4.10.1!

Here are the highlights of this release:
 - Incremental Java compilation by default
 - Periodic Gradle caches cleanup
 - Gradle Kotlin DSL 1.0-RC6
 - Nested included builds
 - SNAPSHOT plugin versions in the `plugins {}` block

For more details see https://docs.gradle.org/4.10.1/release-notes.html

Starting a Gradle Daemon (subsequent builds will be faster)

> Configure project :react-native-auth0
WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
To determine what is calling variant.getJavaCompile(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.

> Transform okhttp-urlconnection.jar (com.squareup.okhttp3:okhttp-urlconnection:3.12.1) with JetifyTransform
ERROR: [TAG] Failed to resolve variable '${animal.sniffer.version}'
ERROR: [TAG] Failed to resolve variable '${project.groupId}'
ERROR: [TAG] Failed to resolve variable '${project.version}'
ERROR: [TAG] Failed to resolve variable '${project.groupId}'
ERROR: [TAG] Failed to resolve variable '${project.version}'
ERROR: [TAG] Failed to resolve variable '${project.groupId}'
ERROR: [TAG] Failed to resolve variable '${project.version}'
ERROR: [TAG] Failed to resolve variable '${project.groupId}'
ERROR: [TAG] Failed to resolve variable '${project.version}'> Task :@react-native-community_async-storage:compileDebugJavaWithJavac

> Task :amazon-cognito-identity-js:compileDebugJavaWithJavac

> Task :app:generateDebugBuildConfig FAILED
66 actionable tasks: 56 executed, 10 up-to-date
warning: [options] source value 7 is obsolete and will be removed in a future release
warning: [options] target value 7 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options. 
3 warnings
warning: [options] source value 7 is obsolete and will be removed in a future release
warning: [options] target value 7 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options. 
3 warnings

FAILURE: Build failed with an exception.

* What went wrong:
java.io.IOException: Unable to delete directory C:\Users\PP\pp-app\android\app\build\generated\source\buildConfig\debug\com.
> Unable to delete directory C:\Users\PP\pp-app\android\app\build\generated\source\buildConfig\debug\com.

* 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 2m 33s

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
warning: [options] source value 7 is obsolete and will be removed in a future release
warning: [options] target value 7 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
warning: [options] source value 7 is obsolete and will be removed in a future release
warning: [options] target value 7 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
3 warnings

FAILURE: Build failed with an exception.

* What went wrong:
java.io.IOException: Unable to delete directory C:\Users\PP\pp-app\android\app\build\generated\source\buildConfig\debug\com.
> Unable to delete directory C:\Users\PP\pp-app\android\app\build\generated\source\buildConfig\debug\com.

* 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 2m 33s

    at checkExecSyncError (child_process.js:629:11)
    at execFileSync (child_process.js:647:13)
    at runOnAllDevices (C:\Users\PP\pp-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:74:39)
    at buildAndRun (C:\Users\PP\pp-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:158:41)
    at then.result (C:\Users\PP\pp-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:125:12)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Equivalent of console.log on Android

$
0
0

I am developing using React Native CLI as I need some Native Libraries in Android and iOS. Because of this I needed to use react-native link packagename

I then find out that the exposed methods for the Native Module in that package is not enough and I need to add some methods in the Native Module in Java (Android). Because of this I need to be able to debug in Java while I'm running React Native. I have tried System.out.println and it does not work. How can I log some result or message in Java when it is being called in a React Native project????

React Native: How to currently accept all license agreements on Android

$
0
0

I am trying to run react-native run-android and I get this error message:

  • What went wrong: A problem occurred configuring project ':RNSwipeView'.

    You have not accepted the license agreements of the following SDK components: [Android SDK Platform 23, Android SDK Build-Tools 26.0.2]. Before building your project, you need to accept the license agreements and complete the installation of the missing components using the Android Studio SDK Manager. Alternatively, to learn how to transfer the license agreements from one workstation to another, go to http://d.android.com/r/studio-ui/export-licenses.html

I tried going to the link provided which redirected me to a more current link provided which instructed me to go to Tools > Android > SDK Manager. I did not find that in the current project I am working on: And you can see for yourself:

enter image description here

So I decided to open a brand new project and I did find the SDK Manager:

enter image description here

Where in there is there a box to tick off license agreements? I could not locate one.

I have also tried the following:

I was able to supposedly accept licenses this way:

cd ~/Library/Android/sdk/tools/bin
➜  bin ./sdkmanager --licenses
Warning: File /Users/danale/.android/repositories.cfg could not be loaded.
All SDK package licenses accepted.======] 100% Computing updates...

When I tried running react-native run-android, I got the same error again.

So I tried it this way according to this answer (Automatically accept all SDK licences):

✗ yes | sudo ~/Library/Android/sdk/tools/bin/sdkmanager --licenses
Password:
Warning: File /var/root/.android/repositories.cfg could not be loaded.
All SDK package licenses accepted.======] 100% Computing updates...

Ran react-native run-android and continued to get the same error you see above.

I tried following Sarats answer: License for package Android SDK Platform 23 not accepted

only to be met with this error:

The "android" command is deprecated.
For manual SDK, AVD, and project management, please use Android Studio.
For command-line tools, use tools/bin/sdkmanager and tools/bin/avdmanager
*************************************************************************
"android" SDK commands can be translated to sdkmanager commands on a best-effort basis.
Continue? (This prompt can be suppressed with the --use-sdk-wrapper command-line argument
or by setting the USE_SDK_WRAPPER environment variable) [y/N]: /usr/local/share/android-sdk/tools/android: line 118: ${trysdkresponse,,}: bad substitution
Invalid or unsupported command "update sdk"

Supported commands are:
android list target
android list avd
android list device
android create avd
android move avd
android delete avd
android list sdk
android update sdk

How can I accept these license agreements?

React native, get size of bottom tab and set Fixed position for screen

$
0
0

I am using import {createMaterialBottomTabNavigator} from '@react-navigation/material-bottom-tabs';

export default class TabBar extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {        
    return (
      <Tab.Navigator style={styles.tab}>
        <Tab.Screen name="Home" component={HomeScreen} style={styles.window}/>
        <Tab.Screen name="Profile" component={ProfileScreen} style={styles.window}/>
        <Tab.Screen name="Cue" component={NewCueScreen} style={styles.window}/>
      </Tab.Navigator>
    );   
  }
}

I would like to set all the child component size so that it is never greater than width of the screen-tab size so that no component shall appear BEHIND the tab.

Here is a drawing of what I meant.

enter image description here

Can't access "sdkmanager" in the Command Prompt

$
0
0

I'm starting to learn JavaScript and React Native (but like REALLY starting). I'm following a course on Udemy and I got stuck on a part where I need to accept some licenses using the "sdkmanager --licenses" command line on the cmd. Cmd tells me that "sdk manager path not recognized as an internal or external command". I tried moving on with the course, but a few steps later, cmd printed this:

"FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring project ':app'. Failed to install the following Android SDK packages as some licences have not been accepted."

I looked for some answers online, but couldn't fix it. I tried some things related to Environment Variables and some things saying the path of the sdkmanager shouldn't conatain white spaces or non ascii characters, but it didn't fixed.

Any help is appreciated! :)

Thanksssss!

PS: I just reseted my computer and followed every step, installed Node.js, JDK, Android Studio, VSCode and all the things the course asked me to.


React Native Android Studio Project Dependencies

$
0
0

I'm very new at Android Development, and i had to use RN to shorten the amount time to complete the project (as it's very very tight). But i'm wondering whenever i open Android Studio, the project file / folder / dependency structure looks like the image below. I don't know why it is getting duplicated and if it probably does affect my build output. Can someone please tell me if this is alright or how to remove those of duplicated?

project files

Note: Don't judge me, it is my dev buddy on this project who's very fond of pulling every npm package there is.

Thanks a lot in advance!

How to get current country of Device in React Native (iOS and Android)?

$
0
0

I am trying to get current country of device in but didn't find anything. Is there something to do so in React Native? I tried using react-native-device-info but it is also not supporting but in previous version it can be get by getDeviceCountry(). Now for the latest version it is showing error:

TypeError: _reactNativeDeviceInfo.default.getDeviceCountry is not a function. (In '_reactNativeDeviceInfo.default.getDeviceCountry()', '_reactNativeDeviceInfo.default.getDeviceCountry' is undefined)

Include react-vr in react-native

$
0
0

I would like to know if it's possible to integrate a react vr tour inside an Android and/or iOS app developed with react native. If so, how I can do it?

This is just an idea but I haven't found a real solution on-line.

Thanks for the attention.

(I'm Italian. Excuse me if you do not understand my English)

How can i make a progress bar with tracker and percent?

$
0
0

I need to make a progress bar like this in the design and it will show me percentage, I am new to react native and I don't know how to develop it enter image description here

React Native - Sliding up Panel does not work on android

$
0
0

Does Anyone knows why the panel is not showing on android when I click on the button? I'm using https://www.npmjs.com/package/rn-sliding-up-panel btw. Please feel free to tell me, if you have any other recommended sliding panel library.

    ...
    <Button title="Show panel" onPress={() => _panel.show(400)} />
    ...
    <SlidingUpPanel
              style={{borderTopLeftRadius: 10}}
              ref={c => (_panel = c)}>
              <View
                style={{
                  flex: 1,
                  backgroundColor: 'white',
                  alignItems: 'center',
                  borderTopRightRadius: 18,
                  borderTopLeftRadius: 18,
                }}>
                <Text>Header</Text>
                <Text>Content</Text>
                <Button title="Hide" onPress={() => _panel.hide()} />
              </View>
    </SlidingUpPanel>

enter image description here

Understanding adb logcat and how to filter from a example

$
0
0

I am using Android's adb logcat for my React Native development. This is a sample of what is outputted by adb logcat:

03-19 16:47:01.168 14818 15029 I ReactNativeJS: inside f1
03-19 16:47:01.198 14818 15029 I ReactNativeJS: inside swe_rise_trans of index.js
03-19 16:47:01.218 14818 15030 D THIS IS MY TAG: HELLO WORLD
03-19 16:47:01.398 14818 15029 I ReactNativeJS: 'temp', 2444663.426169321
03-19 16:47:01.508 14818 15029 I ReactNativeJS: 'julday_of_sunrise_before_birth', 2444663.426169321

The first 2 columns are date and time....what about 3rd (14818) and 4th (15029) and 5th (I for some and D for some)??

The 6th is the Tag is it???

I have tried filtering this by doing:

adb logcat -s "THIS IS MY TAG"

instead of just adb logcat but when I filter with the above code I only get:

--------- beginning of main
--------- beginning of system

I would like to show all ouput with "THIS IS MY TAG" and "ReactNativeJS" only since the rest are just unnecessary noises....below is the complete adb logcat I had:

03-19 16:47:00.748  1334  1334 D StatusBar.NetworkController: refreshNwBoosterIndicator - setNWBoosterIndicators(false)
03-19 16:47:00.748  1334  1334 D StatusBar.NetworkController: refreshNwBoosterIndicator - setNWBoosterIndicators(false)
03-19 16:47:00.748  1334  1334 D StatusBar.NetworkController: refreshNwBoosterIndicator - setNWBoosterIndicators(false)
03-19 16:47:00.748  1334  1334 D StatusBar.NetworkController: refreshNwBoosterIndicator - setNWBoosterIndicators(false)
03-19 16:47:00.908 14818 15029 I ReactNativeJS: 'julday', 2444664.3090046295
03-19 16:47:00.968 14818 15029 I ReactNativeJS: 'next', 2444664.3090046295
03-19 16:47:01.058   340   810 V audio_hw_primary: out_standby: enter: usecase(1: low-latency-playback)
03-19 16:47:01.108   340   810 V audio_hw_primary: stop_output_stream: enter: usecase(1: low-latency-playback)
03-19 16:47:01.108   340   810 V audio_hw_primary: disable_audio_route: enter: usecase(1)
03-19 16:47:01.108   340   810 V audio_hw_primary: disable_audio_route: reset mixer path: low-latency-playback
03-19 16:47:01.108   340   810 D audio_route: ++++ audio_route_update_mixer ==============
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: SLIMBUS_0_RX Audio Mixer MultiMedia5
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: value: 0
03-19 16:47:01.108   340   810 D audio_route: ------ audio_route_update_mixer ==============
03-19 16:47:01.108   340   810 V audio_hw_primary: disable_audio_route: exit
03-19 16:47:01.108   340   810 V audio_hw_primary: disable_snd_device: snd_device(2: speaker)
03-19 16:47:01.108   340   810 D audio_route: ++++ audio_route_update_mixer ==============
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: SPK DRV Volume
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: value: 0
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: RX7 Digital Volume
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: value: 0
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: COMP0 Switch
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: value: 0
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: RX7 MIX1 INP1, value: 0
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: DAC1 Switch
03-19 16:47:01.108   340   810 D audio_route: Setting mixer control: value: 0
03-19 16:47:01.108   340   810 D audio_route: ------ audio_route_update_mixer ==============
03-19 16:47:01.108   340   810 V audio_hw_primary: stop_output_stream: exit: status(0)
03-19 16:47:01.108   340   810 V audio_hw_primary: out_standby: exit
03-19 16:47:01.168 14818 15029 I ReactNativeJS: inside f1
03-19 16:47:01.198 14818 15029 I ReactNativeJS: inside swe_rise_trans of index.js
03-19 16:47:01.218 14818 15030 D THIS IS MY TAG: HELLO WORLD
03-19 16:47:01.398 14818 15029 I ReactNativeJS: 'temp', 2444663.426169321
03-19 16:47:01.508 14818 15029 I ReactNativeJS: 'julday_of_sunrise_before_birth', 2444663.426169321

`react-native-camera` returns a data.uri but image cannot be accessed (no such file or directory)

$
0
0

I would appreciate any help on this. I'm using react-native-camera and when I get the URI of the image taken using takePictureAsync() method, I can't access that image.

I took the photo and navigate to the next screen, passing the image data as the params:

  const data = await this.camera.takePictureAsync(options);
  console.log(data);
  this.props.navigation.navigate('FFV', {
    postItem: data.uri
  });

In the next screen (FFV) I am loading the photo into <Image/> ,it works if I pass the base64 of the image, but doesn't work if I just pass the URI.

<Image style={styles.imagePreview}
          source={{ isStatic:true, uri: postItem }}
          resizeMode="contain"
 />

The image doesn't render and if I try to save the file using CameraRoll, I get "No such file or directory".

First the image data is printed out, second is the error accessing the file

I've tested on the emulator and on physical device - same problem. It doesn't seem to be related to WRITE_EXTERNAL_STORAGE permission, because after I granted the permissions, the ENOENT error occurs.

I check the cache of the app on the phone, and it doesn't have those files, does it mean it's not writing it? If there were issues with the RNCamera I would think the URI wouldn't be returned successfully.

"react-native": "0.57.1",
"react-native-camera": "^1.3.0",

Any help would be much appreciated!


getting error when try to run android react-native project

$
0
0

When i want run react-native run-android command i see

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag. Jetifier found 998 file(s) to forward-jetify. Using 12 workers... info JS server already running. info Installing the app...

FAILURE: Build failed with an exception.

  • Where: Build file 'C:\tmpProjets\beetv-app\node_modules\react-native-reanimated\android\build.gradle' line: 58

  • What went wrong: A problem occurred configuring project ':react-native-reanimated'.

    Cp65001

  • 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 8s

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

FAILURE: Build failed with an exception.

  • Where: Build file 'C:\tmpProjets\beetv-app\node_modules\react-native-reanimated\android\build.gradle' line: 58

  • What went wrong: A problem occurred configuring project ':react-native-reanimated'.

    Cp65001

  • 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 8s

at checkExecSyncError (child_process.js:611:11)
at execFileSync (child_process.js:629:15)
at runOnAllDevices (C:\tmpProjets\beetv-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:39)
at buildAndRun (C:\tmpProjets\beetv-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:179:41)
at C:\tmpProjets\beetv-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:133:12
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Command.handleAction (C:\tmpProjets\beetv-app\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:182:9)

npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! BeeTVApp@0.0.1 android: react-native run-android npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the BeeTVApp@0.0.1 android script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Blerr\AppData\Roaming\npm-cache_logs\2020-03-19T10_46_33_609Z-debug.log

On state upadte React native setState method not calling render function

$
0
0

Scenario:: I am trying to make a todo list app using react native, in which I store the input data that is the particular 'todo' in the AsyncStorage.

Now when I try to change the items in the state the render method gets called and the view that is the list gets updated.

But when the mylist is Null that is AsyncStorage is empty I change the status to in the state to Null expecting it render again and show that Hurray !! No todos left!!.

Code Snippet where I update the state:

 if(filtered.length === 0){
      console.log('Before Updating state ',this.state);
      this.setState({
        status :'Null',
        items: [],
        blank : 1,
      })
      console.log('After Updating state ',this.state);

App.js

import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  AsyncStorage,
  Alert,
  ScrollView
} from "react-native";
import {
  Appbar,
  IconButton,
  TextInput,
  Button,
  Card,
  List
} from "react-native-paper";
export default class App extends Component {
  async componentDidMount() {
    if (await JSON.parse(await AsyncStorage.getItem("mylist")).length) {
      this.array = await JSON.parse(await AsyncStorage.getItem("mylist"));
      this.setState({
        items: await JSON.parse(await AsyncStorage.getItem("mylist"))
      });
    } else {
      this.setState({
        status: "Null"
      });
    }
    this.id = this.array.length - 1;
  }
  array = [];
  id = 0;
  state = {
    items: [{ id: 0, data: "No todos today!!!" }],
    text: "",
    blank: ""
  };
  handleDelete = async id => {
    const objectarray = await JSON.parse(await AsyncStorage.getItem("mylist"));
    const filtered = objectarray.filter(data => {
      if (data.id === id) {
        return false;
      } else {
        return true;
      }
    });
    // console.log('Filtered array of objects':filtered)
    await AsyncStorage.setItem("mylist", JSON.stringify(filtered));
    this.setState({
      items: await JSON.parse(await AsyncStorage.getItem("mylist"))
    });
    if (filtered.length === 0) {
      console.log("Before Updating state ", this.state);
      this.setState({
        status: "Null",
        items: [],
        blank: 1
      });
      console.log("After Updating state ", this.state);
    }
    this.array = await JSON.parse(await AsyncStorage.getItem("mylist"));
  };
  storedata = async () => {
    // console.log(e.target);
    if (this.state.text !== "") {
      this.id = this.id + 1;
      this.array.push({ id: this.id, data: this.state.text });
      this.setState({
        text: "",
        status: ""
      });
      await AsyncStorage.setItem("mylist", JSON.stringify(this.array));
      this.array = await JSON.parse(await AsyncStorage.getItem("mylist"));
      this.setState({
        items: await JSON.parse(await AsyncStorage.getItem("mylist"))
      });
    } else {
      Alert.alert("Alert", "Field Empty");
    }
  };

  render() {
    var list = this.state.items.map(iterator => {
      console.log("I am in there in the list");
      if (this.state.status !== "Null") {
        console.log("i am in the list if ");
        return (
          <View>
            <Card key={iterator.id} style={{ margin: 10 }}>
              <List.Item
                title={iterator.data}
                left={() => <List.Icon icon="label" />}
                right={() => (
                  <IconButton
                    icon="delete"
                    animated="true"
                    onPress={() => this.handleDelete(iterator.id)}
                  />
                )}
              />
            </Card>
          </View>
        );
      } else {
        console.log("i am in the list else");
        return (
          <View>
            <Card key="Null" style={{ margin: 10 }}>
              <List.Item
                title="Hurray !! No todos left!!"
                left={() => <List.Icon icon="label" />}
              />
            </Card>
          </View>
        );
      }
    });

    return (
      <View style={styles.container}>
        <Appbar.Header>
          <Appbar.Content title="My Todos" subtitle="Todos" />
        </Appbar.Header>
        <View style={{ backgroundColor: "#fff" }}>
          <TextInput
            label="Add Todo"
            mode="outlined"
            value={this.state.text}
            color="white"
            style={{ margin: 30 }}
            onChangeText={text => this.setState({ text: text, blank: "" })}
          />
          <Button
            mode="outlined"
            icon="label"
            onPress={this.storedata}
            style={{ marginLeft: 30, marginRight: 30, marginBottom: 30 }}
          >
            Add Todos
          </Button>
        </View>
        <View style={{ flex: 1 }}>
          <ScrollView>{list}</ScrollView>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#d3d3d3"
  }
});

My console :

enter image description here

I am a beginner to React Native and would appreciate any help and suggestions.
Thanks in advance.

Android failed to load JS bundle

$
0
0

I'm trying to run AwesomeProject on my Nexus5 (android 5.1.1).

I'm able to build the project and install it on the device. But when I run it, I got a red screen saying

Unable to download JS bundle. Did you forget to start the development server or connect your device?

In react native iOS, I can choose to load jsbundle offline. How can I do the same thing for Android? (Or at least, where can I configure the server address?)

Update

To run with local server, run the following commands under your react-native project root directory

  1. react-native start > /dev/null 2>&1 &
  2. adb reverse tcp:8081 tcp:8081

please take a look at dsissitka's answer for more details.

To run without a server, bundle the jsfile into the apk by running:

  1. create an assets folder under android/app/src/main
  2. curl "http://localhost:8081/index.android.bundle?platform=android" -o "android/app/src/main/assets/index.android.bundle"

please take a look at kzzzf's answer for more details.

Custom font not working in React Native

$
0
0

I want to use a font from google fonts in my app. Here is the font.

I have placed the .ttf file in app/fonts.

package.json:

{
    "name": "xxx",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "rnpm": {
        "assets": ["./app/fonts"]
    },
    "jest": {
        "preset": "react-native",
        "moduleNameMapper": {
            "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
            "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
        }
    },
    "dependencies": {
        "flow-typed": "^2.0.0",
        "immutable": "^3.8.1",
        "react": "~15.4.1",
        "react-native": "0.42.0",
        "react-native-vector-icons": "^4.0.0",
        "react-redux": "^5.0.3",
        "redux": "^3.6.0",
        "redux-immutable": "^4.0.0",
        "redux-observable": "^0.14.1",
        "rxjs": "^5.2.0"
    },
    "devDependencies": {
        "babel-eslint": "^7.1.1",
        "babel-jest": "19.0.0",
        "babel-preset-react-native": "1.9.1",
        "eslint": "^3.17.0",
        "eslint-plugin-flowtype": "^2.30.3",
        "eslint-plugin-jsx": "^0.0.2",
        "eslint-plugin-react": "^6.10.0",
        "eslint-plugin-react-native": "^2.3.1",
        "flow-bin": "^0.42.0",
        "jest": "19.0.2",
        "jest-cli": "^19.0.2",
        "react-test-renderer": "~15.4.1",
        "redux-devtools": "^3.3.2",
        "remote-redux-devtools": "^0.5.7"
    }
}

then ran react-native link.

Then use the font in my app:

import { View, Text } from 'react-native'
import React from 'react'
import Width from '../width/Width'
import Shape from '../shape/Shape'
import Height from '../height/Height'
import Thickness from '../thickness/Thickness'

export const Volcalc = () => (
  <View style={styles.container}>
    <Text style={styles.text}>SHAPE</Text>
    <Shape />
    <Text style={styles.text}>HEIGHT</Text>
    <Height />
    <Text style={styles.text}>WIDTH</Text>
    <Width />
    <Text style={styles.text}>THICKNESS</Text>
    <Thickness />
  </View>
)

const $mainColor = '#00d1b2'
const styles = {
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: $mainColor
  },
  text: {
    textAlign: 'center',
    color: 'rgba(255, 255, 255, 0.9)',
    fontSize: 15,
    fontFamily: 'Orbitron'
  }
}

In android it doesn't show the new font but has no error. In ios it has error:

Unrecognised font family "Orbitron"

What am I doing wrong?

How do I find out the EXACT value to place in fontFamily: 'xxx'?

Why I cant insert a List in the WritableArray?

$
0
0

I have a case where I want to insert a List in the WritableArray and send it to React-Native but for some reason, it doesn't work, I don't receive anything back in RN:

public static List<Native_DataList> Native_Data = new ArrayList<>();

The reason why I am using WriteableArray is because that's the only way to transport data from Native to React-Native.

@ReactMethod
public void getData(Callback callback){
    if(!Native_Data.isEmpty()){
        WritableArray nativeArray = Arguments.fromList(Native_Data); //this doesnt work
        callback.invoke(nativeArray);
    }
}

It fails with this error: Unknown value type class com.myprojectname.KeepAliveService$Native_DataList

I am doing exactly the same thing in another case but I am using ArrayList instead and works:

public static ArrayList<String> jsonArray = new ArrayList<>();

And this is the function being called from React-Native:

@ReactMethod
public void getData(Callback callback) {
    ArrayList<String> jsonArray = jsonArray ;
    WritableArray nativeArray = Arguments.fromList(jsonArray);
    callback.invoke(nativeArray);
}

Any suggestions?!

Viewing all 29726 articles
Browse latest View live