尝试恢复领域后崩溃

时间:2018-02-13 08:57:16

标签: android realm

我尝试使用Realm为我的Android应用程序实现备份/恢复功能。从备份恢复数据后,如果我尝试访问任何信息(可以从领域请求数据),应用程序崩溃A/libc: Fatal signal 7 (SIGBUS), code 2, fault addr 0x9694d000 in tid 5047 (...), pid 5047 (...)

请记住,重新打开应用后,数据会被恢复(因此备份/恢复会在崩溃后按预期工作)

这是我的RealmBackup班级

public class RealmBackup {

    private final static String TAG = RealmBackup.class.getName();

    private Context context;
    private Realm realm;

    public RealmBackup(Context context) {
        this.realm = Realm.getInstance(Realm.getDefaultConfiguration());
        this.context = context;
    }

    public void backup() {

        File exportRealmFile = null;

        File exportRealmPATH = context.getExternalFilesDir(null);
        String exportRealmFileName = "default.realm";


        // create a backup file
        exportRealmFile = new File(exportRealmPATH, exportRealmFileName);

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

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

        String msg = "File exported to Path: " + context.getExternalFilesDir(null);

        realm.close();

    }

    public void restore() {

        //Restore
        File exportRealmPATH = context.getExternalFilesDir(null);
        String FileName = "default.realm";

        String restoreFilePath = context.getExternalFilesDir(null) + "/" + FileName;

        copyBundledRealmFile(restoreFilePath, FileName);

    }

    private void copyBundledRealmFile(String oldFilePath, String outFileName) {
        try {
            File file = new File(context.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();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String dbPath() {

        return realm.getPath();
    }
}

每当我尝试备份/恢复数据时,我只需拨打realmBackup.backup()restore即可。问题,我相信在使用新数据进行恢复后必须重新打开这个领域,但是,我不确定如何做到这一点,我已尝试使用是否

    Realm.init(this);
    RealmConfiguration config = new RealmConfiguration
            .Builder()
            .deleteRealmIfMigrationNeeded()
            .build();
    Realm.setDefaultConfiguration(config);

或仅仅是realm = Realm.getDefaultInstance();,但这并不是很有效。

2 个答案:

答案 0 :(得分:0)

清除项目,卸载重新安装该应用。

答案 1 :(得分:0)

您不能只删除并覆盖打开的Realm作为“恢复”,您必须首先确保Realm.getGlobalInstanceCount(Realm.getDefaultConfiguration()) == 0

为此,您必须在打开的实例上调用realm.close()

此外,如果使用新架构更新了应用,则deleteIfMigrationNeeded会删除您的备份,因此请注意