简体   繁体   中英

Restore Realm DB from SD Card/External Storage Android

I have a situation where i prompt user whether to backup their messages or no with the google backup service. I am successfully backing up the current realm database onto the SD card from where the backup to google service will happen. But yet i though about the scenario where i want to actually restore the database from SD card to the current Realm Instance,meaning replace the current realm file with the one which is available on the SD Card.

In the older versions i saw that Realm gave a way to specify a custom path from which realm would read the database file,but in this new one i see none of it.

Any help please?

CREATE BACKUP FILE

public void backup() {
    try {
        // create a backup file
        File exportRealmFile;
        exportRealmFile = new File(EXPORT_REALM_PATH, EXPORT_REALM_FILE_NAME);

        // if backup file already exists, delete it
        exportRealmFile.delete();

        // copy current realm to backup file
        realm.writeCopyTo(exportRealmFile);

    } catch (IOException e) {
        e.printStackTrace();
    }
    realm.close();
}

RESTORE

private String copyBundledRealmFile(String oldFilePath, String outFileName) {
    try {
        File file = new File(activity.getApplicationContext().getFilesDir(), outFileName);

        FileOutputStream outputStream = new FileOutputStream(file);

        FileInputStream inputStream = new FileInputStream(new File(oldFilePath));

        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buf)) > 0) {
            outputStream.write(buf, 0, bytesRead);
        }
        outputStream.close();
        return file.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Hope this help.

Credit to link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM