Android Realm默认数据库清除

时间:2015-12-24 06:33:15

标签: android realm

如何在android中清除默认域数据库?我尝试了以下代码,但无法解析方法deleteRealmFile。

方法1:

try {
   Realm.deleteRealmFile(context);
  //Realm file has been deleted.

} catch (Exception ex){
   ex.printStackTrace();
  //No Realm file to remove.
}

我尝试使用配置删除。

方法2:

try {
     Realm.deleteRealm(realm.getConfiguration());
     //Realm file has been deleted.
} catch (Exception ex){
     ex.printStackTrace();
     //No Realm file to remove.
}

但是给出错误:

java.lang.IllegalStateException: It's not allowed to delete the file associated with an open Realm. Remember to close() all the instances of the Realm before deleting its file.

2 个答案:

答案 0 :(得分:6)

Realm.deleteRealm(realm.getConfiguration());之前添加realm.close(),如下所示,它就像魅力一样

try {
      realm.close()
      Realm.deleteRealm(realm.getConfiguration());
                //Realm file has been deleted.
} catch (Exception ex){
                ex.printStackTrace();
                //No Realm file to remove.
}

答案 1 :(得分:2)

如上所述,您必须关闭所有引用特定域文件的Realm实例。

这意味着,如果你已经打电话

Realm realm = Realm.getInstance(config);

你必须在删除它之前关闭它。

realm.close();

Realm实例基于引用计数器,因此请确保每个getInstance都匹配close

这非常重要,否则可能会发生内存泄漏。 有关示例,请参阅https://realm.io/docs/java/latest/#controlling-the-lifecycle-of-realm-instances