bergie3000
bergie3000

Reputation: 1131

How do I create a Realm DB for a React Native app?

Maybe I'm thinking of this the wrong way, but how do I create a pre-populated Realm DB? For example, let's say I want to create a dictionary with 1000 words and definitions in it. The user can change the definitions from within the app, but initially the DB will have default definitions.

Can I create a .realm file with the 1000 words and definitions and include it in my app?

FYI: I am using Realm with React Native and I am currently testing using emulator -avd CordovaAVD to launch my Android emulator.

Upvotes: 3

Views: 1566

Answers (1)

bergie3000
bergie3000

Reputation: 1131

I think I've figured this out so I'll post my solution in case anyone else might find it useful.

I have a function that will populate a Realm DB. Once I run that function, however, I want to grab that static DB and use it instead of generating the DB every time the app starts up. That's what prompted my effort. However, these steps will also be useful if you just want to back up a DB.

I am primarily testing using an emulator, but I think these steps will work if you test on an actual device.

To grab the Realm DB from the emulator:

  1. Find the path to your realm file within the phone by adding this somewhere in your code:
    let YourRealmDB = new Realm({schema: [YourSchema]});
    console.log('YourRealmDB path =', YourRealmDB.path);
  1. The path will be something like
    /data/data/(package.name)/files/(filename).realm
    "filename" will probably be "default"
  2. From the command line, run
    adb exec-out run-as (package.name) cat files/(filename).realm > (filename).realm
  3. This will copy your Realm db to your current directory

Now, to use that DB in your app:

  1. Create a realm object:
    let YourRealmDB = new Realm({schema: [YourSchema]});
  2. Set the objects path to your DB:
    YourRealmDB.defaultPath = 'path/to/your/db/(filename).realm';

NOTE: If you use a 'local' DB like this and your app performs a write operation, it will not write to your local DB. It will write to the db at YourRealmDB.path. So if you want to copy or view the updated DB, you will need to run adb exec-out run-as (package.name) cat files/(filename).realm > (filename).realm again to get the most current version of your DB.

I hope that helps. It took me quite a while to piece that all together.

Upvotes: 4

Related Questions