Realm-java: Realm instance has already been closed, making it unusable

Created on 6 Feb 2017  ·  8Comments  ·  Source: realm/realm-java

https://stackoverflow.com/questions/42057566/realm-instance-has-already-been-closed-making-it-unusable

Sorry about linking my stackoverflow question but it seemed easier.

T-Help

Most helpful comment

Since DataRepository keeps PoliticoDataRepository instance to a static field, DataRepository.getInstance() might return old PoliticoDataRepository instance which contain closed Realm instance.
You should remove static field of dataRepository in DataRepository.

public static PoliticoDataRepository getInstance(Realm realm) {
    if (dataRepository == null)
        dataRepository = new PoliticoDataRepository(realm);

    return dataRepository;
}

This method must return PoliticoDataRepository instance which contain the Realm instance passed as the argument.

All 8 comments

Realm Java 2.2.2 changed major classes to be non-final to help Mockito users. Which version do you use?

@kneth I don't think this question has anything to do with unit testing

@Zhuinden My mistake - I was reading a question at Stackoverflow at the same time. @judemanutd Please ignore my comment ;-)

@kneth if it makes an difference now , i am using 2.3.0

getDefaultInstance() is not really able to return null. In error situations it will throw an exception. Can you set a breakpoint where you call getDefaultInstance() so to be sure that you actually calls it the second time?

@kneth I've got null for Realm.getInstance() before when ˙context.getFilesDir() returned null in Application.onCreate(), but that was back in 0.88.0

Since DataRepository keeps PoliticoDataRepository instance to a static field, DataRepository.getInstance() might return old PoliticoDataRepository instance which contain closed Realm instance.
You should remove static field of dataRepository in DataRepository.

public static PoliticoDataRepository getInstance(Realm realm) {
    if (dataRepository == null)
        dataRepository = new PoliticoDataRepository(realm);

    return dataRepository;
}

This method must return PoliticoDataRepository instance which contain the Realm instance passed as the argument.

Answered here and on GitHub. Closing.

Was this page helpful?
0 / 5 - 0 ratings