Android领域:内存不足

时间:2015-04-15 04:56:33

标签: android realm

使用超过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....
}

1 个答案:

答案 0 :(得分:2)

您持续打开和关闭Realm,同时进行大量小型交易。虽然该模式效率非常低,但它本身不应该导致内存不足。但是如果你在后台线程中运行它,对于每个事务,Realm必须维护原始数据的差异,直到所有线程上的Realms都可以更新(这发生在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();