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

Customise tabs of native base

$
0
0

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

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


React-native keyboard no comma on android Samsung devices in Text Input

$
0
0

I have a React-native app with TextInput and KeyboardAvoidingView. And everywhere it works well except android Samsung devices, especially Samsung A3. Because on this device the keyboard is appearing without a comma, but I need to use it on the screen.

I already tried the steps from this article, removed autoCapitalize="none" from the TextInput component, but it is not working for me.

Can somebody recommend how can I solve it please.[enter image description here

<TextInput
            style={textInput}
            placeholder={props.placeholder}
            underlineColorAndroid='transparent' editable={!props.disabled}
            keyboardType={keyboardType} 
            autoCorrect={false} selection={state.position}
            value={state.value} onChangeText={this._onChangeText}
            onFocus={this._onFocus} onBlur={this._onBlur}
            autoFocus={autoFocus}
          />

How to open drawer navigator not in a screen defined in drawernavigator

$
0
0

is it possible to open a drawer navigator from a screen that I DONT WANT IT TO BE INSIDE MY DRAWER NAVIGATOR

const AppDrawerNavigator = createDrawerNavigator({
  Home:{
    screen:MainStackNavigator,//stack with tab
  },
  Pdf:{
    screen:AnotherScreen
  }
},
{
  drawerPosition: 'left',
  drawerWidth:Dimensions.get('window').width-50,

})

and this is my stacknavigator

const AppStackNavigator = createStackNavigator({
  Main:{screen:AppDrawerNavigator,navigationOptions: {
    header: null,
  }},
  Login:{screen:LoginScreen},

  Map:{screen:MapScreen,navigationOptions:({navigation})=>({
    headerLeft:null,
    headerTransparent:true,
    headerRight:
        <TouchableOpacity
         onPress={()=>navigation.toggleDrawer()}>
           <IconMenu name='menu' size={25} style={{marginRight:20}} />
         </TouchableOpacity>})},
})

I want MapScreen to open the drawer i defined above (its not working , it says navigation is undefined.toggleDrawer() is not a function ,when i click on my IconMenu)

Thnak you

I can not generate a apk release of the project. React-native (Android)

$
0
0

I thank you in advance. I try a problem with a project I am trying to generate the signed apk release but react-native does not generate presenting the following problem:

> Task :react-native-activity-result-deeplink:verifyReleaseResources FAILED

FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':react-native-activity-result-deeplink:verifyReleaseResources'.
> 1 exception was raised by workers:
  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
  error: resource android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
  error: resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values-v26\values-v26.xml:7: error: resource android:attr/colorError not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values-v26\values-v26.xml:11: error: resource android:attr/colorError not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values-v26\values-v26.xml:15: error: style attribute 'android:attr/keyboardNavigationCluster' not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values-v28\values-v28.xml:7: error: resource android:attr/dialogCornerRadius not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values-v28\values-v28.xml:11: error: resource android:attr/dialogCornerRadius not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2740: error: resource android:attr/fontStyle not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2741: error: resource android:attr/font not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2742: error: resource android:attr/fontWeight not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2743: error: resource android:attr/fontVariationSettings not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2744: error: resource android:attr/ttcIndex not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2908: error: resource android:attr/startX not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2911: error: resource android:attr/startY not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2914: error: resource android:attr/endX not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2917: error: resource android:attr/endY not found.
  C:\Users\DEV_8\Documents\testeReactN2\Melica\node_modules\react-native-activity-result-deeplink\android\build\intermediates\res\merged\release\values\values.xml:2925: error: resource android:attr/offset not found.
  error: failed linking references

In Android Studio.

 - already in android studio it generates Configuration 'compile' is
   obsolete and has been replaced with 'implementation' and 'api'.
 - The specified Android SDK Build Tools version (23.0.1) is ignored, as
   it is below the minimum supported version (28.0.3) for Android Gradle
   Plugin 3.4.2.
 - API 'variant.getJavaCompile()' is obsolete and has been replaced with
 - 'variant.getJavaCompileProvider()'.
 - the transform cache was reset.
 - Failed to automatically forward port 8083.

but does not work in android 5.1.1 API 22 which is necessary to work. when I remove react-native-activity-result-deeplink modules "react-native-communication-hardware-getnet" it is back generated by react-native, but these modules are essential for the project to be approved, I don't know what to try anymore.

The bundleRelease generation works normally, and in debug the project works normally as well.

Info Project

info Fetching system and libraries information... System: OS: Windows 10 10.0.18362 CPU: (4) x64 Intel(R) Core(TM) i5-7400 CPU @ 3.00GHz Memory: 874.71 MB / 7.91 GB Binaries: Node: 10.16.0 - C:\Program Files\nodejs\node.EXE Yarn: 1.16.0 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 6.9.0 - C:\Program Files\nodejs\npm.CMD SDKs: Android SDK: API Levels: 22, 23, 25, 27, 28, 29 Build Tools: 23.0.1, 25.0.3, 27.0.3, 28.0.3, 29.0.1, 29.0.2 System Images: android-22 | ARM EABI v7a, android-22 | Google APIs ARM EABI v7a, android-22 | Google APIs Intel x86 Atom, android-22 | Google APIs Intel x86 Atom_64, android-23 | ARM EABI v7a, android-23 | Google APIs ARM EABI v7a, android-25 | Google APIs ARM 64 v8a, android-25 | Google APIs ARM EABI v7a, android-27 | Google APIs Intel x86 Atom, android-27 | Google Play Intel x86 Atom, android-28 | Google APIs Intel x86 Atom, android-29 | Google APIs Intel x86 Atom, android-29 | Google Play Intel x86 Atom Android NDK: 20.0.5594570 IDEs: Android Studio: Version 3.5.0.0 AI-191.8026.42.35.5791312 npmPackages: react: 16.9.0 => 16.9.0 react-native: 0.61.5 => 0.61.5

Reproduce

  1. project link for error reproduction

git clone https://github.com/Andersonfrfilho/Melica

  1. download of keystore and documentation.

https://drive.google.com/open?id=1mB4_06WtZAt36B0ESOUA7aWsM8j90UYC

  1. paste my-upload-key.keystore in android/app
  2. add in android/gradle.properties
MYAPP_UPLOAD_STORE_FILE=my-upload-key.keystore
MYAPP_UPLOAD_KEY_ALIAS=my-key-alias
MYAPP_UPLOAD_STORE_PASSWORD=102030
MYAPP_UPLOAD_KEY_PASSWORD=102030
  1. add android/app/build.gradle

signingConfigs {... release { if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) { storeFile file(MYAPP_UPLOAD_STORE_FILE) storePassword MYAPP_UPLOAD_STORE_PASSWORD keyAlias MYAPP_UPLOAD_KEY_ALIAS keyPassword MYAPP_UPLOAD_KEY_PASSWORD } } }

and

buildTypes { ... release { ... signingConfig signingConfigs.release } } 5. run comand cd android 6. run comand gradlew assembleRelease

How to resolve: Error: spawnSync ./gradlew ENOBUFS

$
0
0

so im trying to build my app on release mode with Docker. When I run it on my machine it works with no problem but when I run it on docker I get this error:

                           Error: spawnSync ./gradlew ENOBUFS
[11:15:54] :     [Step 1/2]     at Object.spawnSync (internal/child_process.js:1041:20)
[11:15:54] :     [Step 1/2]     at spawnSync (child_process.js:607:24)
[11:15:54] :     [Step 1/2]     at execFileSync (child_process.js:634:15)
[11:15:54] :     [Step 1/2]     at runOnAllDevices (/usr/src/app/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:74:39)
[11:15:54] :     [Step 1/2]     at buildAndRun (/usr/src/app/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:158:41)
[11:15:54] :     [Step 1/2]     at /usr/src/app/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:125:12
[11:15:54] :     [Step 1/2]     at processTicksAndRejections (internal/process/task_queues.js:93:5)
[11:15:54] :     [Step 1/2]     at async Command.handleAction (/usr/src/app/node_modules/react-native/node_modules/@react-native-community/cli/build/cliEntry.js:160:7)

when I try to build with develop im getting no problems... another thing I put attention about is when I build my app on docker with ./gradlew installRelease I get no issue but this command never use Jetifier which I really need for my build.

Im attaching my docker file, let me know if you need more files:

ENV SDK_URL "https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip"
ENV ANDROID_HOME /usr/src/app
ENV ANDROID_BUILD_TOOLS_VERSION 28.0.3
ENV ANDROID_VERSION 28
ENV PATH $PATH:$ANDROID_HOME/bin
ARG NODE_VERSION=12.x
WORKDIR /usr/src/app
COPY package*.json ./
RUN cat package.json

# installing android and java
RUN apt update -qq && apt install -qq -y --no-install-recommends \
        apt-transport-https \
        curl \
        build-essential \
        file \
        git \
        openjdk-8-jre \
        gnupg2 \
        python \
        ruby-full \
        openssh-client \
        zip \
        unzip \
        sudo \
    && rm -rf /var/lib/apt/lists/*;

RUN curl -sL -o android.zip ${SDK_URL} && unzip android.zip && rm android.zip
RUN yes | $ANDROID_HOME/tools/bin/sdkmanager --licenses

# install nodejs and yarn packages from nodesource and yarn apt sources
RUN echo "deb https://deb.nodesource.com/node_${NODE_VERSION} stretch main"> /etc/apt/sources.list.d/nodesource.list \
    && echo "deb https://dl.yarnpkg.com/debian/ stable main"> /etc/apt/sources.list.d/yarn.list \
    && curl -sS https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add - \
    && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
    && apt-get update -qq \
    && apt-get install -qq -y --no-install-recommends nodejs yarn \
    && rm -rf /var/lib/apt/lists/*

RUN npm i -g react-native-cli
#installing libraries
RUN npm install
COPY . .

#Create apk and zip it with the current date (UTC)
RUN react-native run-android --variant=release; exit 0
RUN cd android && cd app && cd build && cd outputs && cd apk && cd release && zip -r `(date +%m_%d_%Y__%H:%M)`.zip app-release.apk

#Create a new container from a linux base image that has the aws-cli installed
FROM mesosphere/aws-cli

#Using the alias defined for the first container, copy the contents of the build folder to this container
COPY --from=builder /usr/src/app/android/app/build/outputs/apk/release/ .
COPY --from=builder /usr/src/app/deploy-android-prod.sh .

ENTRYPOINT chmod +x deploy-android-prod.sh && sh ./deploy-android-prod.sh

Thanks for the help

Do OTA updates in Expo work if the app has been published through a bundle?

$
0
0

I am using a lot the fact that expo publish allows OTA ("over the air") updates without the need to go through the normal publishing in the stores (more info in my previous question Do OTA updates in Expo get in motion on the first opening after brand new download from the stores?).

Now I am moving from APK to Android App Bundle, so that I build with:

expo build:android -t app-bundle

Instead of the previous expo build:android -t apk, as described in Expo's documentation Building Standalone Apps.

However, in the article Publishing of their site I also read:

Some native configuration can't be updated by publishing

  • Increment the Expo SDK Version
    (...)
  • Change your bundled assets under assetBundlePatterns

So now I am left wondering: if I publish in the stores with an ".aab" file (Android App Bundle), will it also be available for OTA updates through expo publish?

React Native Expo audio player error - Player does not exist

$
0
0

I'm using react native expo audio in my app, I use createAsync to load the audio in the player but sometimes i get Player doesn't exist error and sometimes it works fine. I'm unable to debug the error. I've also tried expo loadAsync to create and load the audio, it also produces the same error. Heres my code...

    componentWillMount(){
        const audioFileLocation = audioFile;
        const source = audioFileLocation;
        const { sound } = await Audio.Sound.createAsync(
            source,
            {
                progressUpdateIntervalMillis: 1000,
                shouldPlay: false,
                isLooping: false,
            },
            onPlaybackStatusUpdate,
        );
        return sound;Ï
    }

export const playAndPauseSound = async (playbackStatus, playbackInstance) => {
    if (playbackStatus.isPlaying) {
        await playbackInstance.pauseAsync();
    } else {
        if (playbackStatus.positionMillis === playbackStatus.durationMillis) {
            return playbackInstance.replayAsync();
        } else {
            return playbackInstance.playAsync();
        }
    }
}

How can i create new react native App using npx?

$
0
0

I didn't use react-native for a few months. It looks like some things have changed meanwhile. In the official documentation they recommend to uninstall react-native-cli and to usenpx react-native init instead. I did this but ended up with an error because I didn't install that package globally. However, if I install react-native globally, it results in an error when I run the project, saying that I should remove the global package.

What is the proper way to create a react app nowadays?


Hermes is not working in Android with React-native 0.60.2

$
0
0

I've upgraded React-native in existing (not new) project to 0.60.2 by way of changing package.json as written here https://react-native-community.github.io/upgrade-helper/?from=0.59.10&to=0.60.2

In android/app/build.gradle I put: p

roject.ext.react = [
    entryFile: "index.js",
    enableHermes: true  // clean and rebuild if changing
] 

build is successfull, but Hermes does not seems to work, in RN 0.59.0 apk was 29 Mb, now it's 46 Mb.

If I add other changes to build.gradle as here https://react-native-community.github.io/upgrade-helper/?from=0.59.10&to=0.60.2

then I get error: Could not read script '/Users/mac/Desktop/aqua2/node_modules/@react-native-community/cli-platform-android/native_modules.gradle' as it does not exist.

probably because of the last line:

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

how can I solve this?

Date formatting in React Native

$
0
0

I try to format a date time value according to device settings. Whatever I change on the simulator settings or in xCode scheme, I always get US format with date.toLocaleDateString()

So I tried different librairies (moment, react-native-localize, ...) but same, always get US format.

So I tried to set Locale directly with this code :

  const date = new Date(Date.UTC(2019, 11, 26, 14, 5, 0))
  const options = {
     dateStyle: 'medium',
     timeStyle: 'short',
  }
  console.log(date.toLocaleDateString('en-US', options))               // Dec 26, 2019, 3:05 PM
  console.log(date.toLocaleDateString('fr-FR', options))               // Dec 26, 2019, 3:05 PM
  console.log(new Intl.DateTimeFormat('en-US', options).format(date))  // Dec 26, 2019, 3:05 PM
  console.log(new Intl.DateTimeFormat('fr-FR', options).format(date))  // Dec 26, 2019, 3:05 PM

And I still get same results !

What can I do to display my date in other Locale than 'en-US' ?

I don't want to hardcore the format by myself ("DD/MM/YYY HH:mm"), I want to use a Locale I set or better the device's one.

Thanks for advice

react-native android error Failed to install the app native_modules.gradle' line: 170

$
0
0

running react-native run-android in windows but get this error:

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 app:installDebug -PreactNativeDevServerPort=8081 :ReactNative:Unexpected empty result of running 'npx --quiet --no-install react-native config' command from 'null' directory. :ReactNative:Running 'npx --quiet --no-install react-native config' command from 'null' directory failed.

FAILURE: Build failed with an exception.

  • Where: Script '/node_modules/@react-native-community/cli-platform-android/native_modules.gradle' line: 170

  • What went wrong: A problem occurred evaluating script.

    Command config unrecognized. Make sure that you have run npm install and that you are inside a react-native project.

how to share the exported whatsapp docunment to react-native app

$
0
0

I'm new to React native and I want to export my whatsapp chat and share it to my react native app.

There are two packages that can help:

https://www.npmjs.com/package/react-native-file-share-intent
https://github.com/meedan/react-native-share-menu.

I tried with the second package because the first package is not working if we use react-navigation so I installed second package, it is working perfectly fine, but after I'm facing two issues:

  1. If I'm using this package the home-screen icon is not created, I don't know why the icon not created in the home screen, but its placed in the share indent
  2. When I tried to share the text document from the file manager, react native app icon is placed in the share indent and also it's working perfectly. But the same thing I tried it in whats app means it doesn't work. I think when I export from WhatsApp initially its created as a temporary file. That's why my app is not displayed in that sharing indent.

I pushed my code in GitHub repo and the link for the repo is: https://github.com/BalaRajendran/sharemenu-reactnative

App.js - https://github.com/BalaRajendran/sharemenu-reactnative/blob/master/App.js

 export default class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          fileUrl: null,
        };
      }

      componentDidMount() {
        if (RNFileShareIntent) {
          RNFileShareIntent.getFilepath((url) => {
            this.setState({ fileUrl: url });
          })
        }
      }

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.sharemenu">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
      android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            ///changed code according to react-native-share-menu
            <action android:name="android.intent.action.PICK"/>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="text/*" />
            <data android:mimeType="image/*" /> 
            <data android:mimeType="file/*" /> 
            <data android:mimeType="application/*" />
             //
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

so can you please help me with my problem,

React native BLE manager will not stop scanning in assigned time

$
0
0

react-native:0.61 Library used: react-native-ble-manager Issue: I have implemeneted bluetooth scanner using react-native-ble-manager.startScan will be called on render.Mentioned time for scan is 2seconds.But scan wont stop after 2seconds.It stops after 8-9seconds.and if scan is in progress,screen will be hanged.

code snippent:

 class BluetoothScreen extends React.Component {
   constructor(props) {
        super(props);       
        this.state = {
                   scanning: false,
         }
       this.startScan()      
       this.handleDiscoverPeripheral = this.handleDiscoverPeripheral.bind(this);
       this.handlerStop = bleManagerEmitter.addListener('BleManagerStopScan', this.handleStopScan );                
       this.handleAppStateChange = this.handleAppStateChange.bind(this);      
  }
 startScan() {
        console.log("from start scan")
        this.setState({ scanning: false })
        if (!this.state.scanning) {
             BleManager.scan([], 2, false).then((results) => {
                console.log('Scanning...');
                this.setState({ scanning: true });
                this.setState({ isVisibleOne: true })
                return (
                    <View>
                        <Text>Scanning..</Text>
                    </View>
                      )    
               })

    }
     handleStopScan() {
         console.log('Scan is stopped');       
         if (this.state.isVisibleOne === false)
         this.setState({ scanning: false })
     }

}

how to reset gps and remove A-GPS data in android with react native

$
0
0

I have problem using

navigator.geolocation.getCurrentPosition

in react native when i use the apps in another phone the gps always timeout and sometime work. but i try to solve the timeout gps with reset the gps using another apps and the gps work. but how reset the gps and remove A-GPS data using react native?

How to add a View as a Fragment in React Native

$
0
0

I go about adding an Android native View to React Native as follows :

BulbView (The View To Be Added) :

public class BulbView {

    Button button;

    LinearLayout linearLayout;
    LinearLayout linearLayoutContainer;

    public BulbView(Context context) {
        linearLayout = new LinearLayout(context);
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        linearLayoutContainer = new LinearLayout(context);
        linearLayoutContainer.setOrientation(LinearLayout.VERTICAL);

        button = new Button(context);
        button.setText("This button is created from JAVA code");

        linearLayout.addView(button);
        linearLayout.addView(linearLayoutContainer);

        button.setOnClickListener(v -> {
            TextView newTV = new TextView(context);
            newTV.setText("ITEM");
            linearLayoutContainer.addView(newTV);
        });
    }

    public View getButton() {
        return linearLayout;
    }
}  

BulbManager :

public class BulbManager extends SimpleViewManager<View> {
    @Override
    public String getName() {
        return "Bulb";
    }

    @Override
    protected View createViewInstance(ThemedReactContext reactContext) {
        return new BulbView(reactContext).getButton();
    }
} 

The Packager :

public class BulbPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

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

Now we start calling the View :

public class MyReactActivity {
    private Context context;
    private ReactInstanceManager mReactInstanceManager;

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

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

    public View reactJsView() {
        ReactRootView mReactRootView = new ReactRootView(context);
        mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);
        return mReactRootView;
    }
}  

I then call it as a Fragment :

public class TestFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return new MyReactActivity(getContext()).reactJsView();
    }
}  

button.setOnClickListener above does not work as expected when I add the Fragment to a View other than the root view.

getFragmentManager().beginTransaction().add(scrollViewWrapperItems_LL.getId(), new TestFragment()).commit();  

A new Android View (newTV) should be added into a LinearLayout, but that does not seem to happen. However, a linearLayoutContainer.getChildCount() shows that the children's count does increase, but the container view `(linearLayoutContainer)'' does not visually show this. The added child is invisible.

However, adding it to the root view rootContainer_LL below works. It does not work when added into any other child view such as scrollViewWrapperItems_LL.

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

    setMyReactActivity(new MyReactActivity(this));

    rootContainer_LL = new LinearLayout(this);
    rootContainer_LL.setOrientation(LinearLayout.VERTICAL);
    rootContainer_LL.setId(Integer.valueOf(123456));

    scrollViewWrapperItems_LL = new LinearLayout(this);
    scrollViewWrapperItems_LL.setOrientation(LinearLayout.VERTICAL);
    scrollViewWrapperItems_LL.setId(Integer.valueOf(12345));

    myButton = new Button(this);
    myButton.setText("REV _Button");
    myButton.setOnClickListener(v -> {
        getFragmentManager().beginTransaction().add(scrollViewWrapperItems_LL.getId(), new TestFragment()).commit();
    });

    ScrollView scrollView = new ScrollView(this);
    scrollView.addView(scrollViewWrapperItems_LL);

    rootContainer_LL.addView(myButton);
    rootContainer_LL.addView(scrollView);

    setContentView(rootContainer_LL);
}

How can I fix this so that I can add the React native into any child view rather than being restricted to only using it in the root View?

Thank you all in advance.


How to call a JavaScript function from native on a React native app

$
0
0

So I am creating a React native app and I want to call a JavaScript function from the native part of the App.

I know that I can use Native Modules to create a bridge between Native and React Native and I also know that from a Native Module I can emit an event that can be received by React Native.

But, any function call inside a Native Module can only occur from inside the React Native itself, since it needs a React native context, so I can only send an event from a Native Module if the React Native itself calls one of the Native module functions that contains the event emit. Can someone clarify how can I do this?

To be more clear, my final goal is to create an Android library using React native that will be used in an already created Native app, inside my Android Library I want to expose some of my JavaScript components/functions so I can have Native App -> Native part of React Native library -> JavaScript part of React Native library.

Thanks in advance!

Issue with Rotating Image while Saving in React Native

$
0
0

Actual Behaviour :

I am supposed to implement signature pad in landscape-right mode along with a timestamp of signature drawn. Then take a screenshot of the view, and save it in document directory (iOS) or external directory (android) in portrait mode by rotating it. I was successful in implementing signature screen in landscape-right mode using tranform: [{rotate: '90deg"}] css property, and react-native-signature-capture, save the captured screenshot of signature along with the timestamp of signature drawn in local directory using react-native-view-shot cnd convert it into base64 format using react-native-fs. But the saved screenshot is not in portrait mode and i'm trying to rotate the image while saving it in document directory (iOS) or external directory (android) without using any modules. I also tried rotating the image while saving it using canvas context API but could not find way to access canvas in react-native to rotate image while saving it as canvas is HTML DOM related.

Expected Behaviour :

I'm supposed to save the signature drawn along with timestamp in document directory (iOS) or external directory (android) in portrait mode as shown in below screenshot. Can someone help me please. Thanks in advance.

Additional Resources :

Code :

render() {
  return (
    <View
    style={{
      flex: 1,
      flexDirection: 'row',
      overflow: "hidden",
    }}>
    <StatusBar hidden={true} />
    <View
      style={{
        flex: 0.8,
        flexDirection: 'row-reverse',
        marginVertical: width / 18,
        overflow: "hidden",
      }}>
      <ViewShot
        ref="viewShot"
        style={[styles.viewShot, { transform: [{ rotate: this.state.bool && '90deg' }] }]}>
        {/* options={{ width: height, height: width }}> */}
        <SignatureCapture
          style={styles.signature}
          ref={sign => (this.signComponent = sign)}
          onSaveEvent={this._onSaveEvent}
          onDragEvent={this._onDragEvent}
          saveImageFileInExtStorage={true}
          showNativeButtons={false}
          showTitleLabel={false}
          showBorder={false}
          viewMode={'portrait'}
          square={true}
          backgroundColor={"white"}
          maxSize={800}
          rotateClockwise={!!true}
        />
        <View
          ref="timeRef"
          style={{
            width: width / 10,
            height: width / 3,
            justifyContent: 'flex-end',
            flexDirection: 'row-reverse',
          }}>
          <View
            style={{
              width: width / 1.8,
              height: width / 1.8,
              transform: [{ rotate: '-90deg' }],
              overflow: "hidden",
              paddingLeft: width / 18,
              paddingTop: width / 25
            }}>
            <Text style={styles.time}>{this.state.data}</Text>
          </View>
        </View>
      </ViewShot>
      <Image
        ref="imageRef"
        source={{ uri: this.state.imageUri }}
        style={{ transform: [{ rotate: '90deg' }] }}
      />
    </View>
    <View
      style={{
        flex: 0.2,
        alignItems: 'center',
        justifyContent: 'space-around',
        flexDirection: 'column',
        overflow: "hidden",
        backgroundColor: Colors.white,
      }}>
      <View
        style={{
          backgroundColor: Colors.darkGreen,
          width: width / 2,
          justifyContent: 'center',
          alignItems: 'center',
          paddingRight: width / 25,
          paddingVertical: width / 37.5,
          transform: [{ rotate: '-90deg' }],
          overflow: "hidden",
        }}>
        <TouchableOpacity
          hitSlop={{ top: 30, left: 50, right: 50, bottom: 30 }}
          onPress={() => {
            this.saveSign();
          }}>
          <Text style={{ fontSize: width / 18, color: Colors.white }}>Submit </Text>
        </TouchableOpacity>
      </View>
      <View
        style={{
          backgroundColor: '#5476ab',
          width: width / 2,
          justifyContent: 'center',
          alignItems: 'center',
          paddingVertical: width / 37.5,
          transform: [{ rotate: '-90deg' }],
          overflow: "hidden",
        }}>
        <TouchableOpacity
          hitSlop={{ top: 30, left: 50, right: 50, bottom: 30 }}
          onPress={() => {
            this.resetSign();
          }}>
          <Text style={{ fontSize: width / 18, color: Colors.white }}>Clear</Text>
        </TouchableOpacity>
      </View>
      <View
        style={{
          backgroundColor: '#73c5de',
          width: width / 2,
          justifyContent: 'center',
          alignItems: 'center',
          paddingVertical: 10,
          transform: [{ rotate: '-90deg' }],
        }}>
        <TouchableOpacity
          hitSlop={{ top: 30, left: 50, right: 50, bottom: 30 }}
          onPress={() => {
            this.onCancel();
          }}>
          <Text style={{ fontSize: width / 18, color: Colors.white }}>Cancel</Text>
        </TouchableOpacity>
      </View>
    </View>
  </View>

); }

_onSaveEvent(result) {

this.setState({ signature: result.pathName, 
                markResult: result.encoded });

}

_onDragEvent() {

this.setState({ dragged: true });

}

saveSign() {

if (this.state.dragged === true) {
  this.setState({ bool: true });
  this.refs.viewShot.capture().then(uri => {
    this.setState({ imageUri: uri });
    console.log("uri123", uri);
     RNFS.readFile(this.state.imageUri, 
      'base64').then(image => {
      console.log("image123", image);
      this.setState({ sign: image }, () => {
        this.ChangeOrientation();
      });
    });
   });
  } else {
  Alert.alert('NALG', 'Please sign the signature 
  pad to submit');
  }

ChangeOrientation() {

this.props.getSignature(this.state.sign);
this.props.setModalVisible(!this.props.modalVisible);

}

Screenshot of Actual Behaviour :

enter image description here

Screenshot of Expected Behaviour :

enter image description here

Environment:

react-native : 0.61.1

react-native-view-shot : ^3.0.2

react-native-signature-capture : ^0.4.10

react-native-fs : ^2.16.2

Could not run react-native app android. Getting syntax error in the metro bundler which are related to react-native-wheel-picker

$
0
0

I have been trying to run a react native app on my windows laptop. Whenever I use npx react-native run-android I am getting some syntax error as shown below which suggests some error in react-native-wheel-picker package. I tried to debug my going through the library documentation, but everything looks fine. Can anyone help me through this?

enter image description here

enter image description here

Firebase/Crashlytics Dashboard not showing any test crashes for android

$
0
0

I can't understand why it's not showing into Firebase Crashlytics Dashboard ,when i'm trying to link this packages manually i'm getting the error about the duplication. Else i trying to change dependencies for it but i have still have this issue.But in iOS it works good and show me non-fatal errors.

<pre>    I have the issue related with <b>Firebase-Crashlytics</b>
    I am using <b>React Native v0.61.2</b>
    My OS is <b>Mac Mojavi</b>
    And i install <b>Firebase Crashlytics v6</b> from https://invertase.io/oss/react-native-firebase/v6/crashlytics/quick-start
    </pre>

    On Android when i am creating custom errors for testing into Firebase Crashlytics dashboard doesn't show me any types of crashes (look the pic. below)

    [![Errors Not showing][1]][1]


      [1]: https://i.stack.imgur.com/mkS2d.png









    ```

        buildscript {
            ...
            repositories {
                google()
                maven { url 'https://maven.fabric.io/public' }
            }
            dependencies {
                classpath("com.android.tools.build:gradle:3.4.2")
                classpath 'com.google.gms:google-services:4.3.3'
                classpath 'io.fabric.tools:gradle:1.28.1'
            }
        }

        allprojects {
            repositories {
                google()
            }
        } 

    ```
    Here i'm paste the apply plugin: 'io.fabric' and implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'<pre><b>android/app/build.gradle</b></pre>

    ```

        apply plugin: "com.android.application"

        apply plugin: 'io.fabric'
        ....
        dependencies {
            implementation fileTree(dir: "libs", include: ["*.jar"])
            implementation "com.facebook.react:react-native:+"
            implementation 'com.google.firebase:firebase-analytics:17.2.1'
            implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'

        }

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

    ```



    Into package.json i have installed last version of packages
    <pre>
    <b>package.json</b>
    </pre>

    ```

        "dependencies": {
            "@react-native-firebase/app": "^6.2.0",
            "@react-native-firebase/perf": "^6.2.0",
        }

    ```
    NOTE : I don't link manually (as i understood i don't need to do it because it is doing automatically "react-native auto-linking")
<pre>
    <b>Here is my index.js file</b>
    </pre>

    ```

        import React, { Component } from 'react';
        import crashlytics from '@react-native-firebase/crashlytics';


        class App extends Component {
          componentDidMount(){
            // Here is my custom errors
            // But it's now showing in dashboard
            // But in iOS it works good
            crashlytics().recordError(new Error('For test'));
            crashlytics().log('For test');
          }

          render () {
            return (
              <View>
                 <Text>Test</Text>
              </View>
            )
          }
        }

        export default App;

    ```

React Native | App Crash because of "react-native-google-signin"

$
0
0

React Native | react-native-google-signin

After i install react-native-google-sigin with

npm i react-native-google-signin

It suddenly crash ( force close ) right when the app start, I have already did all the steps that is told on the github documentation yet when i run my App it crash instantly, without giving any error in the log. ( neither android-log nor adb logcat *:S ReactNative:V ReactNativeJS:V does )

Here are my codes:

build.gradle

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

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
        googlePlayServicesAuthVersion = "16.0.1" // <--- use this version or newer
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.1")
        classpath 'com.android.tools.build:gradle:3.1.2' // <--- use this version or newer
        classpath 'com.google.gms:google-services:4.1.0' // <--- use this version or newer
        // 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()
    }
}

settings.gradle

rootProject.name = 'App'
include ':react-native-reanimated'
project(':react-native-reanimated').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-reanimated/android')
include ':react-native-gesture-handler'
project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android')
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':react-native-google-signin', ':app'
project(':react-native-google-signin').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-google-signin/android')
include ':app'

app/build.gradle

dependencies {
    implementation project(':react-native-reanimated')
    implementation project(':react-native-gesture-handler')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation(project(":react-native-google-signin"))
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation(project(':react-native-maps')){
            exclude group: 'com.google.android.gms', module: 'play-services-base'
            exclude group: 'com.google.android.gms', module: 'play-services-maps'
        }
        implementation 'com.google.android.gms:play-services-base:10.0.1'
        implementation 'com.google.android.gms:play-services-maps:10.0.1'

    if (enableHermes) {
      def hermesPath = "../../node_modules/hermesvm/android/";
      debugImplementation files(hermesPath + "hermes-debug.aar")
      releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
      implementation jscFlavor
    }
}

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

Can someone help me with this error? because when i uninstall react-native-google-signin with

npm uninstall react-native-google-signin

it works just fine

Viewing all 28480 articles
Browse latest View live


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