Search code examples
androidrealmrealm-mobile-platformrealm-migration

Rename Realm DB file name in Android


I have a Realm DB file, with name "abc.realm". How to change this name to something else? Should I just replace the file name using IO operations or can I do it with migrations? Not able to find any satisfactory answer neither on the web nor on StackOverflow.


Solution

  • Realm stores 2 files, the realm itself and a .lock file. So if you call your realm "abc.realm", then next to this file there is also "abc.realm.lock".

    The way to go about renaming your realm file is,

    1. Make sure you find the location of both files
    2. Rename both files with the same name but keeping the ".lock" extension on the lock file
    3. Modify the path to the realm that you pass to the RealmConfigurationBase inheritor

    Clearly before doing any of this, make sure to backup your database, just in case.

    I don't know what programming language you're writing your android application in, so I'll go with a skeleton in pseudocode

    private void BackupRealmFile(string realmLocation, string saveLocation)
    {
        // make a copy of the file and store it somewhere
    }
    
    void YourMainMethod()
    {
        BackupRealmFile("some/path", "your/backup/path");
    
        IOLib.RenameFile("some/path/abc.realm", "some/path/newName.realm");
        IOLib.RenameFile("some/path/abc.realm.lock", "some/path/newName.realm.lock");
    
        var config = new RealmConfiguration("some/path/newName.realm");
        // maybe some more settings on your conf
    
        var realm = Realm.GetInstance(config);
    }
    

    I hope this helps.