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

React Native adb reverse ENOENT

$
0
0

I am trying to get React-Native to work with Android V4.2.2 (Genymotion) but I am unable to test the app on the Emulator. When I ran react-native run-android, I get this error Could not run adb reverse: spawnSync

Here is a log

JS server already running.
Running /User/Pan/Library/Android/sdk/platform-tools/adb reverse tcp:8081 tcp:8081
Could not run adb reverse: spawnSync /User/Pan/Library/Android/sdk/platform-tools/adb ENOENT
Building and installing the app on the device (cd android && ./gradlew installDebug...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> The SDK directory '/User/Pan/Library/Android/sdk' does not exist.

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

BUILD FAILED

Total time: 3.785 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

NOTE: In the log it saids SDK directory does not exist, I have double check that I do have the SDK installed in that directory.

I found my android emulator when executing adb devices

List of devices attached
192.168.56.101:5555 device

I have tried the following steps from Stack Overflow post, but still no luck https://stackoverflow.com/a/38536290/4540216


How to allow Self-Signed Certificates on Android with React Native

$
0
0

I'm developing a React Native App makes http / https requests. I'm doing for both platforms Android and iOS. I am facing with a problem that don't let me fetch an url with self-signed certificate. I have tested that this is working with other url that aren't self-signed. There is a way to force React Native to trust in Self-Signed certificates?

The error that I get when I execute the fetch() function is this:

TypeError: Network request failed

Here I post my code:

const form = new FormData();
form.append('parameters[ticketPerson]', this.state.ticketPerson);
form.append('rawxmlresponse', 'false');

fetch(this.state.url, {
    method: 'POST', headers: { Connection: 'close' },
    body: form,
})
.then(response => response.json())
.then(async (responseJson) => {
  console.log('repsonse --->', responseJson);
})
.catch((error) => {
  console.log('ERROR ---> ', error);
});

It works on iOS, only fail on Android. And this code works on Android if the url is not a Self-signed certificate.

Avoid responses like "You shouldn't trust in" or "Just Sign it and will work".

import com.android.build.OutputFile error in react-native

$
0
0

First I run a new project

react-native init AwesomeProject --version 0.58.6

(0.59.1 has a bug, but I test this problrm with it)

with react-native run-android I can run it.

In android studio when I sync it, I get an error:

app/build.gradle:

import com.android.build.OutputFile

Error: Cannot resolve symbol 'build'

I use these versions:

ext {
    buildToolsVersion = "28.0.3"
    minSdkVersion = 16
    compileSdkVersion = 28
    targetSdkVersion = 27
    supportLibVersion = "28.0.0"
}
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'

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

The specified Android SDK Build Tools version (28.0.2) is ignored

$
0
0

Im working on react-native project i design to change the icons i followed this video https://www.youtube.com/watch?v=ts98gL1JCQU

then the project cannt run and im getting error enter image description here

WARNING: The specified Android SDK Build Tools version (28.0.2) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.4.2. Android SDK Build Tools 28.0.3 will be used. To suppress this warning, remove "buildToolsVersion '28.0.2'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools. Remove Build Tools version and sync project Affected Modules: rn-secure-storage

Just woundring what i should do , also i dont want rn-secure-storage be affected

Thanks

How to compare selected index of flatlist in next screen with integer number?

$
0
0

As I am a beginner, Very confused about comparison in react native. I have multiple different ImageArray like alphabets, fruits, birds etc. I want to load that according to selected index from flatlist like

if(selectedindex==1){
}
else if(selectedindex==2) 

and so on.

How can I do? Please Help.

Implement ACTION_SHUTDOWN event in react native

$
0
0

How to implement android.intent.action.ACTION_SHUTDOWN event in react native app ? I need to do API call when device shutdown . When I searched for android, I came to know android do provide this action and can write ShutdownReceiver which get notified when device shutdown . But, I couldn't found any plugin/guide for implementing same in react native. Can anyone tell me what is best possible solution to implement same in react native .

react-native: setState() not updating MapView initialRegion with react-native-geolocation-service

$
0
0

In my react-native application, I am react-native-geolocation-service to get user location and display it on the MapView. Below is a simple code I am trying from the various samples available online.

import React, { Component } from 'react'
import 
{
    View,
    StyleSheet,
    Dimensions
} from 'react-native'
import MapView, { PROVIDER_GOOGLE, Marker } from 'react-native-maps';

//import Geolocation from '@react-native-community/geolocation';
import Geolocation from 'react-native-geolocation-service';
import {hasLocationPermission} from '../../../services/Helper'

const {width, height} = Dimensions.get('window')

const SCREEN_HEIGHT = height
const SCREEN_WIDTH = width
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO
const MAP_LOCATION_OPTIONS = { enableHighAccuracy: true, timeout: 20000};

class NearMeTest extends Component {

    constructor(){
        super()
        this.state = {
            initialPosition: {
                latitude: 0,
                longitude: 0,
                latitudeDelta: 0,
                longitudeDelta: 0,
            },
            markers: [{
                title: 'shop1',
                coordinates: {
                  latitude: 12.9782933,
                  longitude: 77.68838
                },
              },
              {
                title: 'shop2',
                coordinates: {
                  latitude: 12.9613824,
                  longitude: 77.7109504
                },
              },
            ]
        }
        this.onCurrentLocationSuccess = this.onCurrentLocationSuccess.bind(this)
        this.onCurrentLocationError = this.onCurrentLocationError.bind(this)
    }

    onCurrentLocationSuccess(pos) {

      var crd = pos.coords;
      var lat = parseFloat(crd.latitude)
      var long = parseFloat(crd.longitude)
      console.log('Your current position is:');
      console.log(`Latitude : ${lat}`);
      console.log(`Longitude: ${long}`);
      console.log(`More or less ${crd.accuracy} meters.`);
      var initialRegion = {
        latitude: lat,
        longitude: long,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      }
      this.setState({initialPosition: initialRegion})
      };

    onCurrentLocationError(err) {
      console.warn(`ERROR(${err.code}): ${err.message}`);
      alert(err.message)
    };

    componentDidMount(){
      if(hasLocationPermission()){
        console.log('Location Permission present, getting current location')
        Geolocation.getCurrentPosition(this.onCurrentLocationSuccess,this.onCurrentLocationError,MAP_LOCATION_OPTIONS)
      }
    }


    render() {
        console.log(this.state.initialPosition)
        return (
            <View style={styles.container}>
                <MapView
                provider={PROVIDER_GOOGLE} // remove if not using Google Maps
                style={styles.map}
                initialRegion={this.state.initialPosition}
                >
                    <Marker
                        coordinate = {{
                            latitude: this.state.initialPosition.latitude,
                            longitude: this.state.initialPosition.longitude, 
                        }}
                    >
                    </Marker>
                    {this.state.markers.map((marker, i) => (
                    <Marker
                        key={i}
                        coordinate={marker.coordinates}
                        title={marker.title}
                    >
                    </Marker>
                    ))}
                </MapView>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
      ...StyleSheet.absoluteFillObject,
      height: SCREEN_HEIGHT,
      width: SCREEN_WIDTH,
      justifyContent: 'flex-end',
      alignItems: 'center',
    },
    map: {
      ...StyleSheet.absoluteFillObject,
    },
   });

export default NearMeTest

I am getting the location in componentDidMount() but when I call setState() to set my initialPosition, I am not seeing it updating in MapView.

Also, another interesting thing is if I use the Geocoder from @react-native-community/geolocation then it works as expected.

I have the location permission and I am using Android Marshmellow device for testing.

How do I request permission for Android Device Location in React Native at run-time?

$
0
0

I have been trying to use React Native 's GeoLocalisation for an Android App. The poorly documentated module is found here https://facebook.github.io/react-native/docs/geolocation.html. According to the documentation, you handle location permissions on Android using the following code in the AndroidManifest.xml file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

However, my online research suggests that the above line of code is useless for versions of ANDROID >= 6.0

As my implementation of GeoLocation is not currently working, I have no other reason but to believe that location permissions are not correctly handled.

How do I successfully request location permission at run-time for React Native Android App ? Thanks in advance !


Cannot read property 'configureProps' of null

$
0
0

When integrating react-native into existing android-app Cannot read property 'configureProps' of null . I got this working with version 0.59 but after upgrade to 0.61 got this problem already fix hermes problem related to this issue https://github.com/facebook/react-native/issues/25985. Maybe the problem is related to autolink packages ? enter image description here

Got this in MainActivity

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SoLoader.init(this, /* native exopackage */ false);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
        int PERMISSION_ALL = 1;
        String[] PERMISSIONS = {
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.RECORD_AUDIO,
        };

        if(!hasPermissions(this, PERMISSIONS)){
            ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                this.checkPermissions(grantResults, "LOCATION");
                return;
            }
        }
    }

    public void checkPermissions(int[] grantResults, String tag){
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.d(tag, grantResults.toString());
            // permission was granted, yay! Do the
            // contacts-related task you need to do.
            Log.d(tag, "Permission was granted");
        } else {
            // permission denied, boo! Disable the
            // functionality that depends on this permission.
            Log.d(tag, "Permission denied");
        }
    }

    public static boolean hasPermissions(Context context, String... permissions) {
        if (context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

}

This is my ReactIntegrationActivity

public class ReactIntegrationActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
    private ReactRootView mReactRootView;
    private final int OVERLAY_PERMISSION_REQ_CODE = 1;
    public ReactInstanceManager mReactInstanceManager;
    private TextView mTextMessage;
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    return true;
                case R.id.navigation_dashboard:
                    Intent intent = new Intent(ReactIntegrationActivity.this, MainActivity.class);
                    startActivity(intent);
                    return true;
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_househoulds);
                    return true;
            }
            return false;
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReactRootView = new ReactRootView(this);

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setCurrentActivity(this)
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackages(this.getPackages())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        // The string here (e.g. "MyReactNativeApp") has to match
        // the string in AppRegistry.registerComponent() in index.js
        mReactRootView.startReactApplication(mReactInstanceManager, "App", null);

        setContentView(mReactRootView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
                    // SYSTEM_ALERT_WINDOW permission not granted
                    Toast.
                            makeText(this, "You cannot open the React Native app as you have denied the permission", Toast.LENGTH_SHORT).show();
                }
            }
        }
        mReactInstanceManager.onActivityResult( this, requestCode, resultCode, data );
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostPause(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostResume(this, this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostDestroy(this);
        }
        if (mReactRootView != null) {
            mReactRootView.unmountReactApplication();
        }
    }


    @Override
    public void onBackPressed() {
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackPressed();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
            mReactInstanceManager.showDevOptionsDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
                new MainReactPackage(),
                new NetInfoPackage(),
                new ReactNativeConfigPackage(),
                new RNGestureHandlerPackage(),
                new CallDetectionManager(getApplication()),
                new ReactNativePushNotificationPackage(),
                new VoicePackage(),
                new SvgPackage(),
                new VectorIconsPackage(),
                new SweeprCloudPackage(),
                new SweeprScanPackage(),
                new SweeprResolutionPackage(),
                new PingTestPackage()
        );
    }
}

Axios POST method: Network Error - React Native

$
0
0

When i send request with my Google Cloud address from postman its ok but from android studio/react-native/axios its give an error.

[Error: Network Error]

This is my code:

constructor(props){
    super(props);
    this.state = {
      email: '',
      password: '',
      error: '',
      loading: false
    };
}

handleLoginUser(){
    const { email, password } = this.state;
    this.setState({ error: '', loading: true });

    axios.post("https://serverip/users/login",
        {
            'email': 'email',
            'password': 'password'
        },
        {
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
            },
        }
    )
    .then(response => {
        console.log(response);
        return response.json();})
    .then(data => {
        if (result.success){
            alert("Login successful");
        }
        else
            alert("Unable to Login");
        })
    .catch((error) => {
      console.log(error);
    });
}

Thanks for your helps.

Using Typekit (Adobe) fonts on React Native project?

$
0
0

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

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

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

keyboardDidHide fires, but does not pass event data on Android

$
0
0

I have added two listeners, for both keyboardDidShow & keyboardDidHide

componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow.bind(this));
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide.bind(this));
  }

When I am trying to hide the keyboard on iOS, the event is passed, no problem and everything works as expected.

However on Android, no event is being received.

  keyboardDidHide(e) {
    console.log("keyboard did hide!");
    console.log(e);
  }

This code gets triggered, but e is null.

This seems related to this other Stack Overflow question, that never seems to have gotten resolved:

KeyboardDidShow/Hide events are not working on Android with adjustResize setting

My Android Manifest file has this line - with the windowSoftInputMode set to adjustPan:

<activity android:theme="@style/SplashTheme" android:name=".MainActivity" android:launchMode="singleTop" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:windowSoftInputMode="adjustPan">

Is all of this correct? Should I be changing any of it?

How to view the changes of an imported file in React-Native?

$
0
0

I have a .js file that stores several json objects that will be used to dynamically create components in various parts of the app. For ex:

import langUtil from '../utilities/langUtil';
export default {
 ...
    DEFAULT_DAY_TIME: {
        "times": [
            {
                "name":langUtil.day_morning,
                "value":"1"
            },
            {
                "name":langUtil.day_afternoon,
                "value":"2"
            },
            {
                "name":langUtil.day_evening,
                "value":"3"
            }
        ],
    ...
}

langUtil uses the 'react-native-localization' package to give translations in various languages. Therefore, if the language is currently set to be English, it will show the text as "Morning" and if its French, "Matin" and so on. This actually works with no issue if I use langUtil.day_morning inside a component:

<Text>{langUtil.day_morning}</Text> //will show the correct language when language is changed

Because my app has an option to change language, I would like it to update all the text to the new language, and as mentioned, this works for when langUtil is used inside a component.

However, if I do this in render:

render() {
    const { DEFAULT_DAY_TIME} = json_constants;

and json_constants is imported like this:

import json_constants from '../../assets/json_constants';

It will not update when the text upon language change. I assume its because its already been imported and the language has already been set. So it will not re-import the file. I'm wondering if there is a way to change the language for those objects, or do I need to rethink the whole setup?

By the way, here is a simplified example of how those objects are used:

{DEFAULT_DAY_TIME.map(item => {
        return (
                <View key={item.value} style={styles.label} >
                        <Text>{item.name}</Text>
                </View>
        );
})}

Java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/FirebaseApp

$
0
0

Screenshot from Android Studio

Google Play Services

This is React Native project. I have an error after successful build in Android Studio Emulator:

java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/FirebaseApp

My files:

package.json:

...
"react-native": "^0.55.3",
"react-native-camera": "1.1.2",
"react-native-check-box": "^2.1.0",
"react-native-extended-stylesheet": "^0.8.1",
"react-native-firebase": "^4.2.0",
"react-native-geocoder": "^0.5.0",
"react-native-git-upgrade": "^0.2.7",
"react-native-htmlview": "^0.12.1",
"react-native-image-picker": "^0.26.10",
"react-native-linear-gradient": "^2.4.0",
"react-native-local-storage": "^1.5.2",
"react-native-maps": "^0.21.0",
"react-native-modal": "^5.4.0",
"react-native-modal-dropdown": "^0.6.1",
"react-native-read-more-text": "^1.0.0",
"react-native-router-flux": "^4.0.0-beta.27",
"react-native-svg-image": "^2.0.1",
"react-native-text-input-mask": "^0.7.0",
...

android/app/build.gradle:

...    
android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"

    defaultConfig {
        applicationId "com.something.anything"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        multiDexEnabled true
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile(project(':react-native-firebase')) {
        transitive = false
    }
    compile project(':react-native-geocoder')
    compile(project(':react-native-maps')) {
      exclude group: 'com.google.android.gms', module: 'play-services-base'
      exclude group: 'com.google.android.gms', module: 'play-services-maps'
      exclude group: 'com.google.android.gms', module: 'play-services-location'
    }

    compile 'com.google.android.gms:play-services-base:15.+'
    compile 'com.google.android.gms:play-services-maps:15.+'
    compile 'com.google.android.gms:play-services-location:15.+'
    compile (project(':react-native-camera')) {
    exclude group: "com.google.android.gms"
    compile 'com.android.support:exifinterface:25.+'
    compile ('com.google.android.gms:play-services-vision:12.0.1') {
        force = true
        }
    }
    compile project(':react-native-text-input-mask')
    compile project(':react-native-linear-gradient')
    compile project(':react-native-image-picker')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
}

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

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

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

subprojects {
  project.configurations.all {
     resolutionStrategy.eachDependency { details ->
        if (details.requested.group == 'com.android.support'&& !details.requested.name.contains('multidex')
        ) {
           details.useVersion "27.1.0"
        }
     }
  }
}

I've tried a lot of solutions but nothing helped.

When sending from react native tcp client to a node js tcp server, the first message is sent successfully the second throws error

$
0
0

enter image description here

Im using react-native-tcp-socket and my code is identical to what is in their docs. I am able to make a connection and send/receive one message, but when I try to connect again, I get this error. I am working on an android simulator and connecting to a node js server.

var client = TcpSocket.createConnection(options);

client.on('data', function(data) {
  console.log('message was received', data);
});

client.on('error', function(error) {
  console.log(error);
});

client.on('close', function(){
  console.log('Connection closed!');
});

// Write on the socket
client.write('COORDINATE_MOVE ELEV:' + this.state.elevation + 'AZIM:' + this.state.azimuth + 'ID:todd');

// Close socket
client.destroy();

Styling react-native Navigation Drawer Items

$
0
0

How To styling react-native navigation drawer item's Text.I go through the Documentation but i didnt able to find correct way to do that

Navigation Documentation

This is My AppContainer

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { View, Text, Button, StyleSheet } from 'react-native';
import { bindActionCreators } from 'redux';
import { ActionCreators } from '../actions';
import Home_ from './Home';
import About from './About';
//Add navigation
import { DrawerNavigator, DrawerItems} from 'react-navigation'

const cunstomeDrawerContentComponent = (props) => (
    <View style={{flex: 1, color: 'red',
        textAlign: 'center',
        fontSize: 30,
        fontFamily: 'cochin',
        letterSpacing: 4}} >
        <DrawerItems {...this.props} />
    </View>
);

const drawerLayout = DrawerNavigator({
    Home: { screen: Home_ },
    About: { screen: About },

});

function mapDispatchToProps(dispatch) {
    return bindActionCreators(ActionCreators, dispatch);
}

const styles = StyleSheet.create({
    container: {
        flex: 1, color: 'red',
        textAlign: 'center',
        fontSize: 30,
        fontFamily: 'cochin',
        letterSpacing: 4
    }


});

export default connect((state) => { return {} }, mapDispatchToProps)(drawerLayout);

How to open APK file and install?

$
0
0

My code:

import RNFS from 'react-native-fs';

const downloadDest = `${RNFS.CachesDirectoryPath}/${(Math.random() * 1000) | 0}.apk`;
const options = {
    fromUrl: url,
    toFile: downloadDest,
    background: true,
};
RNFS.downloadFile().promise.then(res => {
  // How to open APK file and install?
})

How do I open an APK file and install it?

I have tried using Linking.openURL (downloadDest) but that didn't work.

How to close webview after the work is done in react native

$
0
0

I am using following code to render a webview:

const someHTMLFile = require('./somefile.html')
render() {
  return (
     <View style={{flex: 1}}>
      <WebView
          style={{flex: 1}}
          source={someHTMLFile}
          ref={( webView ) => this.webView = webView}
      />      
    </View>
  );
}

In this html file, there is a form which is automatically submitted when the webview loads (with some data sent from reactnative part of code) and in the end, the file is redirected to a specific url, where some processing is done (on the send data), and right now, it returns nothing. So the screen goes blank.

So, at this point, I want to close the webview and take the user back to my reactnative app.. So, how can I do that? any suggestions?

react-native-fs path not found?

$
0
0
import RNFS from 'react-native-fs';

var path = RNFS.DocumentDirectoryPath + '/test.txt';
RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
  .then(success => {
    console.log('FILE WRITTEN!');
  })
  .catch(err => {
    console.log(err.message);
});

console.log(RNFS.DocumentDirectoryPath)
// /data/data/xxx.xxx.xxx/files/

But I didn't find a path/file like /data/xxx.xxx.xxx/files/ in the data directory of the mobile phone

But the entry in the code exists

RNFS.readDir(RNFS.DocumentDirectoryPath).then(result => {
  console.log('DocumentDirectoryPath GOT RESULT', result);
});

I want to know what is the path of RNFS.DocumentDirectoryPath in the phone?

How to load react-native(Android) a bundle remotely

$
0
0

I created an android module in my APP with react-native Android, In my case, I am trying to load a JS bundle file remotely, but it's always loading from localhost, and I see the config to bundle's location is hard coded in DevServerHelper.java, the bundle file in my APP's assets folder is read-only when APP running so I can't modify it dynamically.

so can I load the bundle file remotely? If not, how can I implementation an upgrade feature in APP use react-native?

thanks a lot!

Viewing all 28479 articles
Browse latest View live


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