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

How to fetch private network using android and react-native

$
0
0

I'm currently trying to access local network (192.168.1.**) from my android react-native application.

I've no access to the internet but only some website from my company. (I can access them throw chrome, opera, edge but not throw firefox).

When I try to fetch the url "constellation.tech" (192.168.1.223) (which is one of the accessible website) I got this error :

TypeError: Network request failed
        at XMLHttpRequest.xhr.onerror (7d73db73-6dce-4f17-a442-ddd610de0c2a:24524)
        at XMLHttpRequest.dispatchEvent (7d73db73-6dce-4f17-a442-ddd610de0c2a:29723)
        at XMLHttpRequest.setReadyState (7d73db73-6dce-4f17-a442-ddd610de0c2a:29085)
        at XMLHttpRequest.__didCompleteResponse (7d73db73-6dce-4f17-a442-ddd610de0c2a:28912)
        at 7d73db73-6dce-4f17-a442-ddd610de0c2a:29022
        at RCTDeviceEventEmitter.emit (7d73db73-6dce-4f17-a442-ddd610de0c2a:2913)
        at MessageQueue.__callFunction (7d73db73-6dce-4f17-a442-ddd610de0c2a:2218)
        at 7d73db73-6dce-4f17-a442-ddd610de0c2a:1960
        at MessageQueue.__guard (7d73db73-6dce-4f17-a442-ddd610de0c2a:2172)
    at MessageQueue.callFunctionReturnFlushedQueue (7d73db73-6dce-4f17-a442-ddd610de0c2a:1959)

I've already search on some post, most of them are about fetching localhost, I've tried some workaround like using axios, set :

<application
   ...
  android:usesCleartextTraffic="true"
 ...>

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

Does someone have any information, or a solution to this problem ?

Thanks for reading :)


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 set borderRadius on a react-native modal?

$
0
0

I have a react-native Modal, I would like to render it with rounded corners like this: Modal example

but if I define it like this:

<Modal
       style={{
                borderTopLeftRadius: 10,
                borderTopRightRadius: 10,
                overflow: 'hidden',
            }}

nothing happens (at least on Android). I also tried to wrap the Modal with a View with the same style but with no more success.

What am I doing wrong?

react navigation modal buttons are un-clickable on android

$
0
0

I'm testing my app on Android only to realize that it's impossible to close or click on any button inside my React Navigation modal on Android, when it works on iOS.

I can't find a reason for this and so here is my code:

The modal:

Modal.js

return (
  <View style={styles.container}>

    <TouchableWithoutFeedback
      onPress={() => console.log('loook')}
      style={{
        margin: 10,
        padding: 10,
        backgroundColor: Colors.brandBlue,
        borderRadius: 50,
      }}
    >
      <Text style={{ color: Colors.white }}>Click me</Text>
    </TouchableWithoutFeedback>
  </View>
);

Navigation.js

const HomeStack = createStackNavigator(
  {
    Main: CombineStack,
    Modal: Modal,
  },
  {
    mode: 'modal',
    headerMode: 'none',
    transparentCard: true,
  }
)

Calling Native Java method from React Native in Javascript

$
0
0

I am trying to call an Android native method showJ from Javascript in React Native but I keep getting the error :

2019-12-10 20:22:31.959 24712-24861/com.example.myapplication E/ReactNativeJS: TypeError: Cannot read property 'showJ' of null
2019-12-10 20:22:31.976 24712-24712/com.example.myapplication E/unknown:ReactNative: Unable to launch redbox because react activity is not available, here is the error that redbox would've displayed: TypeError: Cannot read property 'showJ' of null, js engine: hermes  

Any help resolving this will be greatly appreciated. Thank you all in advance.

This is how I go about it :

public class MainActivity extends AppCompatActivity {

    Button myButton;
    public static int OVERLAY_PERMISSION_REQ_CODE = 2;

    LinearLayout rootContainer_LL;
    LinearLayout scrollViewWrapperItems_LL;

    MyReactView myReactView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        rootContainer_LL = new LinearLayout(this);

        myButton = new Button(this);
        myButton.setText("REV _Button");
        myButton.setOnClickListener(v -> viewOnClick());

        rootContainer_LL.addView(myButton);
        setContentView(rootContainer_LL);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
            }
        }

        myReactView = new MyReactView(this);
    }

    void viewOnClick() {
        rootContainer_LL.addView(myReactView.reactJsView());
    }

    @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...
                }
            }
        }
    }
}  

Get the React view :

public class MyReactView {

    private Context context;
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;

    public MyReactView(Context context) {
        this.context = context;

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(((Activity) context).getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
                .build();
    }

    public View reactJsView() {
        Bundle initialProperties = new Bundle();
        initialProperties.putString("var_1", "Im the first var");

        mReactRootView = new ReactRootView(context);
        mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", initialProperties);

        return mReactRootView;
    }

}  

ThenMainApplication

public class MainApplication extends Application implements ReactApplication {

    private final ReactNativeHost mReactNativeHost =
            new ReactNativeHost(this) {
                @Override
                public boolean getUseDeveloperSupport() {
                    return BuildConfig.DEBUG;
                }

                @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());
                    // return packages;

                    packages.add(new CustomToastPackage());

                    Log.v("MyApp", "APP CALL FUNCS");

                    return packages;
                }

                @Override
                protected String getJSMainModuleName() {
                    return "index";
                }
            };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
    }
}  

Then I try adopting the implementation as directed in The Toast Module

ToastModule

public class ToastModule extends ReactContextBaseJavaModule {
    private static ReactApplicationContext reactContext;

    private static final String DURATION_SHORT_KEY = "SHORT";
    private static final String DURATION_LONG_KEY = "LONG";

    ToastModule(ReactApplicationContext context) {
        super(context);
        reactContext = context;
    }

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

    @Override
    public Map<String, Object> getConstants() {
        final Map<String, Object> constants = new HashMap<>();
        constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
        constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
        return constants;
    }

    @ReactMethod
    public void showJ(String message, int duration) {
        Toast.makeText(getReactApplicationContext(), message, duration).show();
    }
}  

CustomToastPackage

public class CustomToastPackage implements ReactPackage {

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

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();

        modules.add(new ToastModule(reactContext));

        return modules;
    }
}  

The Javascript call

import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;  

then . . .

import ToastExample from './ToastExample';

ToastExample.showJ('Awesome', ToastExample.SHORT);  

UPDATE

The full javascript implementation :

import React, {Component} from 'react';
import {AppRegistry, StyleSheet, Text, View, TouchableOpacity} from 'react-native';

import {name as appName} from './app.json';

import ToastExample from './ToastExample';

class HelloWorld extends Component {

    async sayHiFromJava() {
        ToastExample.showJ('Awesome', ToastExample.SHORT);
    }

    render() {
        return (
            <View style={
                styles.container
            }>
                <TouchableOpacity style={
                        styles.btnStyleH
                    }
                    onPress={
                        this.sayHiFromJava
                }>
                    <View>
                        <Text style={
                            styles.btnStyle
                        }>...PUSH</Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }
}
var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'flex-start',
        flexDirection: 'row'
    },
    btnStyle: {
        fontSize: 10,
        justifyContent: 'flex-start'
    }
});

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

then :ToastExample.js

import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;

How to add border radius on the App main view?

$
0
0

How can I add a border radius on the main view that surround the AppContainer like Snapchat ?

Snapchat has it in all its app

I tried to put a 'border-radius: 20' on the view that surround the AppContainer but it doesn't work.

Snapchat border radius

react native secureTextEntry not working on android

$
0
0

I am trying to use react-native secureTextEntry to hide my password and confirm password fields during registration.I'm using custom InputBox component for textInput.below is my code,

<InputBox 
                error={this.state.PwordError} 
                keyboardType={'default'} 
                onChangeText={Pword =>
                    this.setState({
                        Pword
                    })
                } 
                secureTextEntry={true}
                value={this.state.Pword} 
                pHolder={"Password"} 
                color={'white'} />
            <View style={styles.spacer} />
            <InputBox 
                error={this.state.CPwordError} 
                keyboardType={'default'} 
                onChangeText={CPword =>
                    this.setState({
                        CPword
                    })
                } 
                secureTextEntry={true}
                value={this.state.CPword} 
                pHolder={"Confirm Password"} 
                color={'white'} />

The first textbox works fine when a password is entered it show as dots, but the confirm password field does not work. does anyone have an idea why this could occur?

This is the input box that is referred by the above code

<TextInput 
                    underlineColorAndroid="transparent"
                    placeholder={this.props.pHolder} 
                    placeholderTextColor={this.props.color === 'white' ? 'black':"white" } 
                    {...this.props}
                    style={this.props.color == 'white' ? styles.ReginputStyle : styles.inputStyle} 

                    /> 

i am using,

"react": "16.5.0",
"react-native": "0.57.1",

I was able to fix this by removing the keyboardType={'default'} code from my input component. Even though the problem is fixed i would like to know why the first secureTextEntry box worked while the other didn't, as both of them were identical except for the value. can any one give a reason to why this could occur,

thanks.

Duplicate class com.google.android.gms.gcm.PendingCallback in modules firebase and play-services-gcm

$
0
0

When executing react-native run-android I get the following error:

> Task :app:checkDebugDuplicateClasses FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkDebugDuplicateClasses'.
> 1 exception was raised by workers:
  java.lang.RuntimeException: Duplicate class com.google.android.gms.gcm.PendingCallback found in modules jetified-firebase-jobdispatcher-0.6.0-runtime.jar (com.firebase:firebase-jobdispatcher:0.6.0) and jetified-play-services-gcm-16.1.0-runtime.jar (com.google.android.gms:play-services-gcm:16.1.0)

Apparently there are two kinds of two packages that are in conflict. I've been days trying to compile my existing react-native project but I haven't made progress.

I did the update of my project from android to AndroidX through Android Studio through

Refactor -> Migrate to AndroidX

All the dependencies were overwritten by the new ones (with androidx, in theory).

I also already have the flags in my gradle.properties:

android.enableJetifier = true 
android.useAndroidX = true

Also after this I run on console: npx jetify

Any idea why this is happening to me, below I leave my configuration files.

android/build.gradle

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

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 29
        targetSdkVersion = 28 //SE COMENTO ESTO POR ERRORES EN EL SYNC DE ANDROID STUDIO. 2019-07-11
        //targetSdkVersion = 29
        supportLibVersion = "28.0.0"
        googlePlayServicesAuthVersion = "15.0.1" // <--- use this version or newer
        pdfViewer = "2.8.2" //https://www.npmjs.com/package/react-native-view-pdf
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.google.gms:google-services:4.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
    subprojects {
        afterEvaluate { project ->
            if (project.hasProperty("android")) {
                android {
                    compileSdkVersion rootProject.ext.compileSdkVersion
                    buildToolsVersion rootProject.ext.buildToolsVersion
                }
            }
        }

    }
}

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"
        }
        maven {
            url "https://maven.google.com"
        }
        maven { url "https://www.jitpack.io" }
    }
}
//task wrapper(type: Wrapper) {
wrapper{
    gradleVersion = '4.7'
    distributionUrl = distributionUrl.replace("bin", "all")
}

android/app/build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile



project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"


def enableSeparateBuildPerCPUArchitecture = false


def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion '29.0.0'

    defaultConfig {
        applicationId "com.blablabla"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 15
        versionName "0.31"
        vectorDrawables.useSupportLibrary = true
    }
    signingConfigs {
        debug {
            storeFile file('keystore/debug.keystore')
            keyAlias 'androiddebugkey'
            keyPassword 'android'
            storePassword 'android'
        }
        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", "arm64-v8a"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3]
            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
            }
        }
    }


    //Se agregan estos packagingOptions porque no hace Build al haber instalado librerias de carga de fotos (react-native-crop-picker) 2019-12-10
     packagingOptions {
         exclude 'META-INF/DEPENDENCIES'
         exclude 'META-INF/LICENSE'
         exclude 'META-INF/LICENSE.txt'
         exclude 'META-INF/license.txt'
         exclude 'META-INF/NOTICE'
         exclude 'META-INF/NOTICE.txt'
         exclude 'META-INF/notice.txt'
         exclude 'META-INF/ASL2.0'
       }

}

dependencies {
    implementation project(':react-native-fast-image')
    implementation project(':react-native-image-crop-picker')
    implementation project(':react-native-device-info')
    implementation project(':react-native-view-pdf')
    implementation project(':amazon-cognito-identity-js')
    implementation project(':@aws-amplify_pushnotification')
    implementation project(':react-native-webview')
    implementation project(':react-native-google-signin')
    implementation project(':react-native-splash-screen')
    implementation project(':react-native-keychain')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-vector-icons')
    implementation fileTree(include: ['*.jar'], dir: 'libs')  
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'com.facebook.react:react-native:+'
    // From node_modules
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation 'com.google.firebase:firebase-messaging:17.4.0'
}


// 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'
}

apply plugin: 'com.google.gms.google-services' // <--- this should be the last line

Android app uploaded as .aab to play store crashes while opening, if I upload as apk it works fine [closed]

$
0
0

When I upload the app as aab it crashes with error:

Unable to load script. make sure you are running meters server

But when I upload it as apk it works just fine.

Why Axios on Android doesn't provide response on 400 Error?

$
0
0

I'm using React Native & Axios and they work perfect on iOS but unfortunately on Android, Axios doesn't return error response from the server.

Here is my server response as raw data. Checked it with proxy and it returns without any problem (and works on iOS too)

HTTP/1.1 400 Bad Request
Date: Tue, 10 Dec 2019 22:07:15 GMT
Server: Apache/2.4.29 (Ubuntu)
Cache-Control: no-cache, private
X-RateLimit-Limit: 200
X-RateLimit-Remaining: 191
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, X-Requested-With, Authorization
Content-Length: 73
Connection: close
Content-Type: application/json

{"errors":{"email":["email registered before."]}}

Here is my _registerUser() function for calling web service

    registerUser = (data) => {
        return axios({
            method: 'post',
            url: getEndpoint() + URLS.register,
            data: data,
            config: { headers: { 'Content-Type': 'multipart/form-data' } }
        })
    };

Here is the part I call registerUser & catching errors. On that part, error is just "Network Error" and doesn't return response key in it as it should (and as does on iOS) What can be the reason for this?

    registerUser(data)
            .then((response) => {
                console.log("HANDLE SUCCESSFUL REGISTER ERE");
            })
            .catch((error) => {
                console.log("HANDLE ERROR HERE");
                console.log("error object");
                console.log(error);
                console.log(JSON.stringify(error));
                console.log("error.response object");
                console.log(error.response);
                console.log("---------");
            });

Thank you very much for your help...

Important addition to my question: I am using interceptors to catch 401 errors like this; could it be related? SELF ANSWER: Removing the interceptor didn't change anything.

axios.interceptors.response.use(undefined,
    error => {
        if ((typeof error.response !== "undefined") && (typeof error.response.status !== "undefined") && error.response.status === 401) {
            console.log("INVALID API TOKEN DETECTED --- REDIRECTING TO LOGIN");

            // do some stuff here

        }
        return Promise.reject(error);
    }
);

minSdk compatibility error setting up react-native-notifications@2.1.3 with react-native 0.60.0

$
0
0

I'm trying to add a push notification system to a react-native project, and I an trying to use react-native-notifications version 2.1.3.

My package.json file looks like this:

"dependencies": {
    "@react-native-community/async-storage": "^1.6.3",
    "jetifier": "^1.6.4",
    "react": "16.8.6",
    "react-native": "0.60.0",
    "react-native-camera": "^3.11.1",
    "react-native-elements": "^1.2.7",
    "react-native-gesture-handler": "^1.5.1",
    "react-native-notifications": "^2.1.3",
    "react-native-permissions": "^2.0.3",
    "react-native-qrcode-scanner": "^1.3.1",
    "react-native-vector-icons": "^6.6.0",
    "react-navigation": "^1.0.0-beta.27",
    "react-redux": "^5.1.2",
    "redux": "^4.0.4",
    "redux-thunk": "^2.3.0",
    "rn-fetch-blob": "^0.10.16"
  },
  "devDependencies": {
    "@babel/core": "7.5.0",
    "@babel/runtime": "7.5.0",
    "@react-native-community/eslint-config": "0.0.3",
    "babel-jest": "24.8.0",
    "eslint": "6.0.1",
    "jest": "24.8.0",
    "metro-react-native-babel-preset": "0.54.1",
    "react-test-renderer": "16.8.6"
  },
  "jest": {
    "preset": "react-native"
  }
}

My project level build.gradle(android/build.gradle) looks like

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.4.1")

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

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

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

        google()
        jcenter()
    }
}
subprojects { subproject ->
    afterEvaluate {
        if ((subproject.plugins.hasPlugin('android') || subproject.plugins.hasPlugin('android-library'))) {
            android {
                variantFilter { variant ->
                    def names = variant.flavors*.name
                    if (names.contains("reactNative59")) {
                        setIgnore(true)
                    }
                }
            }
        }
    }
}

react-native-notifications version 2.1.3 android/build.gradle

buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:4.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

react-native-notifications android/app/build.gradle

apply plugin: 'com.android.library'
apply from: '../prepare-robolectric.gradle'

android {
    compileSdkVersion 27
    buildToolsVersion '28.0.3'

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
    testOptions {
        unitTests.all { t ->
            reports {
                html.enabled true
            }
            testLogging {
                events "PASSED", "SKIPPED", "FAILED", "standardOut", "standardError"
            }
            afterSuite { desc, result ->
                if (!desc.parent) { // will match the outermost suite
                    def output = "      ${result.resultType} (${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)     "
                    def repeatLength = output.length()
                    println '\n\n' + ('-' * repeatLength) + '\n' + output + '\n' + ('-' * repeatLength) + '\n'

                    println "see report at file://${t.reports.html.destination}/index.html"
                }
            }
        }
    }

    flavorDimensions "RNNotifications.reactNativeVersion"
    productFlavors {
        reactNative59 {
            dimension "RNNotifications.reactNativeVersion"
        }
        reactNative60 {
            dimension "RNNotifications.reactNativeVersion"
        }
    }
}

dependencies {
    implementation "com.google.firebase:firebase-messaging:17.3.0"
    implementation 'com.facebook.react:react-native:+'

    // tests
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.robolectric:robolectric:3.5.1'
    testImplementation 'org.assertj:assertj-core:3.8.0'
    testImplementation 'com.squareup.assertj:assertj-android:1.1.1'
    testImplementation 'org.mockito:mockito-core:2.13.0'
}

I know most of the code above is not needed, but I provided in case I had missed something.

My problem is that my project has a minSDK version of 16 but react-native-notifications has a minSDK version of 19. When trying to build I get this output:

* What went wrong:
Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 19 declared in library [:react-native-notifications] Project-Root\node_modules\react-native-notifications\an
droid\app\build\intermediates\library_manifest\reactNative60Debug\AndroidManifest.xml as the library might be using APIs not available in 16
        Suggestion: use a compatible library with a minSdk of at most 16,
                or increase this project's minSdk version to at least 19,
                or use tools:overrideLibrary="com.wix.reactnativenotifications" to force usage (may lead to runtime failures)

* 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 14s

    at checkExecSyncError (child_process.js:621:11)
    at execFileSync (child_process.js:639:15)
    at runOnAllDevices (Project-Root\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:75:39)
    at buildAndRun (Project-Root\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:137:41)
    at Project-Root\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:103:12
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async Command.handleAction (Project-Root\node_modules\react-native\node_modules\@react-native-community\cli\build\cliEntry.js:160:7)

I have looked up solutions online, and I unsuccessfully tried shifting react-native-notifications minSDK version down to 16.

When I try to shift my project's minSDK to 19, I get

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 de
tails.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
C:\Users\nvashakidze\dev\BRAND-NEW\Micromeritics-Final\android\app\build\generated\rncli\src\main\java\com\facebook\react\PackageList.java:66: error: constructor RNNotificationsPackage in class RNNotificationsPackage cannot be applied
 to given types;
      new RNNotificationsPackage(),
      ^
  required: Application
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

If anyone can help me fix this issue, I would really appreciate it.

How to make the Alert / Modal / Dialog service appear when the application is closed react native?

$
0
0

I have a problem, here I made two applications say, seller and buyer. When the buyer pays with the hit API / Socket IO the Seller application displays a popup. These Pop-Up are like phone calls or video calls.

#

Expo error something went wrong could not load exp://127.0.0.1:19000

$
0
0

I don't know what is wrong with expo it was working fine. Expo is not showing me my IP address so that I can connect expo client app with my PC by scanning QR code. I had tried many solution from internet but nothing works. Below is the images of my expo client error image and my browser image.

browser-picture

mobile-picture

How to get BSSID and SSID in android on Expo?

$
0
0

I want to get the BSSID and SSID info of an android mobile. I am developing my application on Expo. Currently I am using react-native-network-info module but its not working.

Image is 90 degree left rotated after encoding to Base64

$
0
0

I am using GalleryIntent to pick an image from the gallery and after that, I am encoding that image to Base64, but in this process after encoding an image to Base64, I saw that image is rotated to 90 degree.

Here is my code:-

public class ImagePickerModule extends ReactContextBaseJavaModule {

    private static final int IMAGE_PICKER_REQUEST = 121;
    private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST";
    private static final String E_PICKER_CANCELLED = "E_PICKER_CANCELLED";
    private static final String E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER";
    private static final String E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND";

    private Promise mPickerPromise;

    private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {

        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) {
            if (requestCode == IMAGE_PICKER_REQUEST) {
                if (mPickerPromise != null) {
                    if (resultCode == Activity.RESULT_CANCELED) {
                        mPickerPromise.reject(E_PICKER_CANCELLED, "Cancelled");
                    } else if (resultCode == Activity.RESULT_OK) {
                        Uri uri = intent.getData();
                        if (uri == null) {
                            mPickerPromise.reject(E_NO_IMAGE_DATA_FOUND, "Cancelled");
                        } else {
                            mPickerPromise.resolve(uri.toString());
                        }
                    }

                    mPickerPromise = null;
                }
            }
        }
    };

    @ReactMethod
    public String encodeImage(String url, final Promise promise) {
        Uri uri = Uri.parse(url);
        byte[] b;
        InputStream imageStream;
        try {
            imageStream = getReactApplicationContext().getContentResolver().openInputStream(uri);
            final Bitmap image = BitmapFactory.decodeStream(imageStream);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 40, baos);
            b = baos.toByteArray();
            try {
                promise.resolve(Base64.encodeToString(b, Base64.DEFAULT));
                image.recycle();
            } catch (OutOfMemoryError e) {
                Log.e("OutOfMemoryError", "encodeImage: e");
            } catch (RuntimeException err) {
                Log.e("RuntimeException", "encodeImage: e");
            }
        } catch (Exception e) {
            promise.reject("File Not Found Exception", "File not Found");
            e.printStackTrace();
        }
        return url;
    }

    ImagePickerModule(ReactApplicationContext reactContext) {
        super(reactContext);
        reactContext.addActivityEventListener(mActivityEventListener);
    }

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

    @ReactMethod
    public void pickImage(final Promise promise) {

        Activity currentActivity = getCurrentActivity();

        if (currentActivity == null) {
            promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
            return;
        }

        if (ContextCompat.checkSelfPermission(currentActivity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(currentActivity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
        }

        // Store the promise to resolve/reject when picker returns data
        mPickerPromise = promise;

        try {
            final Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            currentActivity.startActivityForResult(galleryIntent, IMAGE_PICKER_REQUEST);
        } catch (Exception e) {
            mPickerPromise.reject(E_FAILED_TO_SHOW_PICKER, e);
            mPickerPromise = null;
        }
    }
}

I am using this as a native module in my react native project. I tried this way Android getting an image from gallery comes rotated

but it doesn't help me.

If anyone knows the solution then help me. Thanks in Advance :)


React Native drag down to open a top to bottom sliding sheet, drawer, modal, etc

$
0
0

A bottom sheet, drawer, etc. (lots of names, I'll be calling it sheet) is used a lot in apps and there are a lot of RN packages for it. I need one top-down, not bottom-up. The video below shows what I need, but top-down instead of bottom-up.

https://youtu.be/lMo3KI1-9Ps

The image below is a screenshot of the app. The red bar at the top needs to be pulled down to open a second window (this may be a modal). The sheet must be over the tab navigator at the bottom (Home, Subjects, etc.), and must be able to navigate to another page and back. This bar currently sits on a custom header that's loaded via React Navigation's header object. This header receives the navigation prop from the page it's loaded in from. It's no issue if it basically extends the total height of the header to the full page (this will probably the easiest solution). Must work on both android and iOS. We're using expo.

enter image description here

I noticed this package has a height offset which may be quite useful.

React Native Image Picker: null is not an object (evaluating 'ImagePickerManager.showImagePicker')

$
0
0

I installed react-native-image-picker according to the documentation. When I am trying to select the image from the phone (after hitting the button), the emulator is giving me this error- null is not an object (evaluating 'ImagePickerManager.showImagePicker')

My React native's version is 0.59.8

and image picker's version is 0.28.0

this the code-

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  Button
} from 'react-native';
import ImagePicker from "react-native-image-picker";

export default class App extends Component {

  state = {
    pickedImage: null
  }

  reset = () => {
    this.setState({
      pickedImage: null
    });
  }




pickImageHandler = () => {
    ImagePicker.showImagePicker({title: "Pick an Image", maxWidth: 800, maxHeight: 600}, res => {
      if (res.didCancel) {
        console.log("User cancelled!");
      } else if (res.error) {
        console.log("Error", res.error);
      } else {
        this.setState({
          pickedImage: { uri: res.uri }
        });

      }
    });
  }



       resetHandler = () =>{
            this.reset();
          }

  render() {
    return (
      <View style={styles.container}>
      <Text style={styles.textStyle}>Pick Image From Camera and Gallery </Text>
        <View style={styles.placeholder}>
          <Image source={this.state.pickedImage} style={styles.previewImage} />
        </View>
        <View style={styles.button}>

          <Button title="Pick Image" onPress={this.pickImageHandler} />

          <Button title="Reset" onPress={this.resetHandler} />

         </View>
      </View>
    );
  }
}

Module RCTEventEmitter is not a registered callable module

$
0
0

This problem has already been addressed, but in my case it seems to be of a different type.

App.js Code:

import React, {Component} from 'react';
import { AppRegistry,StyleSheet, Text, View} from 'react-native';


export default class MainApp extends React.Component{

  static navigationOptions = () => ({
    title: "Home",
    headerTintColor:"white",

  })

  render(){
    return(
      <View>
        <Text>Hello World !</Text>
      </View>
    )
  }
}

I have import react native elements and react navigation as libraries using yarn.

Access mobile device's traffic react native

$
0
0

Is there anyway i can access a mobile(Android) device's web traffic i.e. the website url's the user is visiting in the browser, and redirect them to our app. Just like what a VPN does, it gets the request url user has entered and processes it on their own server?

Implement drawer from native base in react native app

$
0
0

I need to use drawer from native base into react native app for both android ios et android. Here is the link for native base http://nativebase.io/docs/v2.0.0/components#drawer and below you'll find my code :

import { Container, Header, Title, Content, Button, Icon, Left,  Body, Text } from 'native-base';
import { Drawer } from 'native-base';    
import SideBar from '../components/SideBar';   
class App extends Component {
        closeDrawer = () => {
        this._drawer._root.close();
    }
    openDrawer = () => {
        alert('open');
        this._drawer._root.open();
    }
    render() {   
        return (
            <Container>
                <Header style={{ backgroundColor: '#C0C0C0' }}>
                    <Left>
                        <Button transparent onPress={this.openDrawer.bind(this)}>
                            <Icon style={style.icon} name='menu'  />
                        </Button>    
                    </Left>
                    <Body style={style.body}>
                    <Title style={{ color: '#FFF'}}> title </Title>
                    </Body>   
                </Header>
                 <Content>
                     <Drawer
                    ref={(ref) => { this._drawer = ref; }}
                    content={<SideBar />} >
                    </Drawer>
                </Content>

            </Container>
        );
    }

the alert in the method open drawer is working fine, so i know it's not a problem in the button.

Viewing all 28480 articles
Browse latest View live


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