记得在所有Realm实例上调用close(),即使我调用close()

clu*_*clu 4 java android realm

我正在看

Remember to call close() on all Realm instances. Realm /data/data/com.org.example/files/default.realm is being finalized without being closed, this can lead to running out of native memory. 
Run Code Online (Sandbox Code Playgroud)

即使我.close()在每次通话后都清楚地打过电话getInstance(realmConfig).

大部分时间它看起来像这样:

Realm realm = Realm.getInstance(realmConfig);
try {
    realm.beginTransaction();
    realm.copyToRealmOrUpdate(someData);
    realm.commitTransaction();
} catch (Exception e) {
    realm.cancelTransaction();
} finally {
    if (realm != null) {
        realm.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

其他时候看起来像(使用Rx Observable Pattern):

@Override
public void call(Subscriber<? super JsonElement> subscriber) {
    SomeJson someJson = Realm.getInstance(mRealmConfig).where(SomeJson.class)
                    .equalTo("type", type)
                    .equalTo("id", id)
                    .findFirst();

    if (someJson == null || !someJson.isDataValid()) {
        Logger.d(TAG, "Did not find value for id: " + id + " for type: " + type);
        subscriber.onNext(null);
        subscriber.onCompleted();
        Realm.getInstance(mRealmConfig).close();
        return;
    }

    JsonElement val = (new JsonParser()).parse(someJson.jsonString);
    subscriber.onNext(val);
    subscriber.onCompleted();
    Realm.getInstance(mRealmConfig).close();
}
Run Code Online (Sandbox Code Playgroud)

知道我为什么还要收到这些警告吗?

use*_*421 6

Realm realm = Realm.getInstance(mRealmConfig);
// ...
Realm.getInstance(mRealmConfig).close();
Run Code Online (Sandbox Code Playgroud)

问题出在这里.你已经获得了另一个 Realm,并关闭了它,但你没有关闭orignal realm.

您应该使用try-with-resources来完成所有这些:

try (Realm realm = Realm.getInstance(realmConfig)) {
    realm.beginTransaction();
    realm.copyToRealmOrUpdate(someData);
    realm.commitTransaction();
} catch (Exception e) {
    realm.cancelTransaction();
}
Run Code Online (Sandbox Code Playgroud)

[请注意,realm在您测试它时,它永远不会为空,如果是它,它将会进一步触发NPE.]

@Override
public void call(Subscriber<? super JsonElement> subscriber) {
    try (Realm realm = Realm.getInstance(mRealmConfig)) {
        SomeJson someJson = realm.where(SomeJson.class)
                    .equalTo("type", type)
                    .equalTo("id", id)
                    .findFirst();

        if (someJson == null || !someJson.isDataValid()) {
            Logger.d(TAG, "Did not find value for id: " + id + " for type: " + type);
            subscriber.onNext(null);
            subscriber.onCompleted();
            return;
        }

        JsonElement val = (new JsonParser()).parse(someJson.jsonString);
        subscriber.onNext(val);
        subscriber.onCompleted();
    }
}
Run Code Online (Sandbox Code Playgroud)