Dedeepthika
Dedeepthika

Reputation: 315

How to close realm object in android

I'm trying to check if any realm object is in transaction, so that I can remove entire DB. But this statement always returns false. Realm.getDefaultInstances().isClose() where I have done wrong. someone explain me please.

 if(!Realm.getDefaultInstances().isInTransaction()){

    Realm.getDefaultInstances().close();
    if(Realm.getDefaultInstances().isClosed()){
       Realm.getDefaultInstance().executeTransaction(new Realm.Transaction(){
                    @Override
                    public void execute(Realm realm) {
                        realm.deleteAll();

                        realm.close();

                    }
                });

          }
    }

Upvotes: 2

Views: 1838

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81539

try(Realm r = Realm.getDefaultInstance()) {
    r.executeTransaction((realm) -> {
        realm.deleteAll();
    }); 
} // <-- auto-close

But you need to call close() for each getInstance() call.

Upvotes: 3

Christian Melchior
Christian Melchior

Reputation: 20126

Realm instances are reference counted, so calling Realm.getDefaultInstance() before each method will increase that count to at least 4 in your example, meaning that you need to call .close() 4 times as well.

Note, that calling close() inside a transaction lambda will cause the transaction to not be committed. The close has to be on the outside.

I would highly recommend reading these two sections about controlling the Realm life cycle:

https://realm.io/docs/java/latest/#closing-realms

https://realm.io/docs/java/latest/#realm-instance-lifecycle

Upvotes: 3

Related Questions