androidrealmrealm-database

How to backup Realm DB in Android before deleting the Realm file. Is there any way to restore the backup file?


I am working on an Android application where I will be deleting Realm before copying the new data to Realm. Is there any way I can take backup of the data before deleting it and restore it back if something is wrong when using realm.copyToRealm() ?


Solution

  • Realm.writeCopyTo might be helpful for this case. You can find doc here.

    //Backup
    Realm orgRealm = Realm.getInstance(orgConfig);
    orgRealm.writeCopyTo(pathToBackup);
    orgRealm.close();
    //Restore
    Realm.deleteRealm(orgConfig);
    Realm backupRealm = Realm.getInstance(backupConfig);
    backupRealm.writeCopyTo(pathToRestore);
    backupRealm.close();
    orgRealm = Realm.getInstance(orgConfig);
    

    But in your case, it would be much simpler and faster to just move your Realm file to a place to backup, and move it back when you want to restore it. To get the Realm file path, try:

    realm.getPath();