JoWeber
JoWeber

Reputation: 68

Using a Singleton for Realm in UI-Thread

I use Realm in a Project. I built this RealmActivity to easily use Realm in code with getActivity.getRealm().

public abstract class RealmActivity extends AppCompatActivity {

private Realm realm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    realm = Realm.getDefaultInstance();
    super.onCreate(savedInstanceState);
}


@Override
protected void onDestroy() {
    super.onDestroy();
    if (!realm.isClosed()) {
        realm.close();
    }
}


public Realm getRealm() {
    return realm;
}

Now I want to delete the Realm-file to clear the data for this session/user. To do this, all RealmInstances have to be closed. I tried to start a Logout-Activity with an intent to clear the activityStack. It works fine for my Nexus 5 (Android 6) but not for my Nexus 4 (Android 5).

My idea was to create a Singleton for the RealmInstance, which used in the UI-Thread

public abstract class RealmActivity extends AppCompatActivity {

private Realm realm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    realm = ManagerLayer.getInstance().getRealm();
    super.onCreate(savedInstanceState);
}


@Override
protected void onDestroy() {
    super.onDestroy();
}


public Realm getRealm() {
    return realm;
}

}

Now, I got only one Instance and can close it before deleting the file. But I never close the RealmInstance when I´m not logging out. Is that an Problem?

But when I clear the ActivityStack and the onDestroy() method isn´t called, the RealmInstance for the Activity gets never closed, too. Right?

Can I use a Singleton for the UI-Thread realmInstance? I never pass it to another Thread and never close it. Or is there another solution to close all RealmInstances to delete the RealmFile?

Upvotes: 2

Views: 687

Answers (1)

droidpl
droidpl

Reputation: 5892

If you want to keep the instance of some object that is needed for the whole application, you should keep this instance in:

  1. The Application class, extending it and setting the android:name in the AndroidManifest.xml.
  2. Another class that is not an Android component, a simple java class.

Talking about lifecycles, if you have some action that closes the Realm instance and this is enough, simply create a clear method in your singleton and call it properly.

If this is not the case, you have to keep in mind that you can never warranty that the onDestroy method is called, but if you don't release the resources because the process has been killed, you don't have to worry at all, since when a process is killed all the objects not persisted will be completely released, even if they are using the filesystem or the network.

Upvotes: 2

Related Questions