迭代超过3000次的使用循环:
for (Element e2 : elinks2) {
AllAuthors allauthor = new AllAuthors();
allauthor.setUrl_base(href.substring(0, href.length() - 1));
allauthor.setAuthor_fio(e2.text().trim());
allauthor.setLetters(e.attr("href"));
Realm realm_2 = null;
try {
realm_2 = Realm.getInstance(new File(func.getFolder("db")), getResources().getString(R.string.app_name_db) + ".realm");
realm_2.beginTransaction();
realm_2.copyToRealmOrUpdate(allauthor);
realm_2.commitTransaction();
} finally {
if(realm_2 != null) {
realm_2.close();
}
}
}
添加(或更新)大约 1000 条记录后出现错误
Out of memory in io_realm_internal_SharedGroup.cpp line 164
在线发誓
realm_2.commitTransaction();
什么建议?
AllAuthors.class:
@RealmClass
public class AllAuthors extends RealmObject {
@PrimaryKey
private String url_base;
private String author_fio;
private String letters;
....Standard getters & setters generated....
}
最佳答案
您不断打开和关闭一个 Realm ,同时进行大量小额交易。虽然该模式效率非常低,但它本身不应导致内存不足。但是,如果您在后台线程中运行它,则对于每个事务 Realm 都必须维护与原始数据的差异,直到所有线程上的 Realm 都可以更新(这发生在 Looper 事件或调用 Realm.refresh() 上) )。我建议重构为以下内容,这既更快又更少占用内存:
Realm realm_2 = Realm.getInstance(new File(func.getFolder("db")), getResources().getString(R.string.app_name_db) + ".realm");
realm_2.beginTransaction();
for (Element e2 : elinks2) {
AllAuthors allauthor = new AllAuthors();
allauthor.setUrl_base(href.substring(0, href.length() - 1));
allauthor.setAuthor_fio(e2.text().trim());
allauthor.setLetters(e.attr("href"));
realm_2.copyToRealmOrUpdate(allauthor);
}
realm_2.commitTransaction();
realm_2.close();
关于Android Realm : Out of memory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29641874/