Search code examples
androidrealm

Realm object not accesible when realm is closed. Android


I'm using Realm for Android.

I have issue (not really a big problem), I have this lines of code:

Account account;
....
realm = Realm.getDefaultInstance();
account = realm.where(Account.class).findFirst();
realm.close();
if (account.getJid().equals(mUser.getText().toString())) { // User is the same as logged before
    launchLogin(mUser.getText().toString().split("@")[0],mPassword.getText().toString());

}

If I launch the app, when the execution arrives to IF statement, it crash because account object does'nt exist. Even when exist accounts in the db. But If move the realm.close() inside the IF, after the launchLogin(..), it works .

What I understand is that account "dissapears" when I close the realm db. and I can get real problem in a future.

So I want to know how can I made "persistent" this type of problem. I mean, close realm after queries and the object still exist after it.


Solution

  • In addition to EpicPandaForces answer, if you really want to close the realm and discard any auto-update advantages Realm offers, you can create an unmanaged copy of the RealmObject using realm.copyFromRealm(realmObject);