Search code examples
androidreact-nativerealm

unknown execution context when import realm in react-native


Im really new to react-native and Im trying to use Realm. I already done the react-native link realm and rnpm link realm. But i get the error unknown execution context when I try to import Realm, heres my index.android.js

import React, { Component } from 'react';
import {
 AppRegistry,
 StyleSheet,
 Text,
 View,
} from 'react-native';
import { TabViewAnimated, TabBar } from 'react-native-tab-view';
import Today from './app/Today'
import Realm from 'realm'
import _ from 'lodash'

const styles = StyleSheet.create({
container: {
    flex: 1,
},
page: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
},
});
export default class ExpenseManagerProject extends Component {
state = {
index: 0,
routes: [
{ key: '1', title: 'Today' },
{ key: '2', title: 'Category' },
{ key: '3', title: 'Date' },
],
};
_handleChangeTab = (index) => {
this.setState({ index });
 };

_renderFooter = (props) => {
  return <TabBar {...props} />;
};

_renderScene = ({ route }) => {
switch (route.key) {
    case '1':
    return <Today/>;
    case '2':
    return <View style={[ styles.page, { backgroundColor: '#673ab7' } ]} />;
    default:
    return null;
}
};

render() {
return (
     <TabViewAnimated
      style={styles.container}
      navigationState={this.state}
      renderScene={this._renderScene}
      renderFooter={this._renderFooter}
      onRequestChangeTab={this._handleChangeTab}
      />
  );
}
}

AppRegistry.registerComponent('ExpenseManagerProject', () => ExpenseManagerProject);

Solution

  • According to documentation:

    Add the following lines to android/settings.gradle:

    gradle include ':realm' project(':realm').projectDir = new File(rootProject.projectDir, '../node_modules/realm/android')
    

    Add the compile line to the dependencies in android/app/build.gradle:

    gradle dependencies { compile project(':realm') }
    

    Add the import and link the package in android/app/src/main/java/com/[your-application-name]/MainApplication.java:

    import io.realm.react.RealmReactPackage; // add this import
    public class MainApplication extends Application implements ReactApplication {
        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                new MainReactPackage(),
                new RealmReactPackage() // add this line
            );
        }
    }
    

    For me, it was only the last step, adding the lines to MainApplication.java, that I had to do, since the other stuff was already present. So make sure you check all the files mentioned.

    If it still does not work, create a new project, add Realm (including the steps above) and add all the files you have previously written.