Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remember to call close() on all Realm instances but everything should be closed

Tags:

android

realm

im having a workflow inside my app where the user can save something and after that a dialog appears with the hint to login. Inside my Android monitor the following Warning shows up: "Remember to call close() on all Realm instances. Realm /data/data/files/default.realm is being finalized without being closed, this can lead to running out of native memory."

Ive read the documentation (https://realm.io/docs/java/latest/) where the advice is to use "try-with-resources" (https://realm.io/docs/java/latest/#closing-realm-instances). So every Realm Transaction is inside

try (Realm realm = Realm.getDefaultInstance()) {
// No need to close the Realm instance manually
}

and inside this block im using

                realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    // do Something
                }
            });

So in conclusion:

try (Realm realm = Realm.getDefaultInstance()) {
 realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    // do Something
                }
            });
}

Can anyone explain to me why this Warning shows up? Ive even tried to add a finally block where i close the Realm instance manually. But this does not avoid the warning. Thanks in advance!

like image 653
Lars Avatar asked Oct 22 '25 23:10

Lars


1 Answers

Ive ended with the following solution. Inside my regular classes i've used the try catch block like this:

try (Realm realm = Realm.getDefaultInstance()) {
   Repository.doSomething(realm);
} catch (Exception e){
   e.printStackTrace();
}

So im using the realm instances in my repository classes and they get closed after they returned the data inside the try catch block.

Thanks for your help!

like image 116
Lars Avatar answered Oct 25 '25 12:10

Lars



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!