1
votes

I want to reuse realm objects which are once removed from database.

Lets say, I have removed one object from database.

Story story = realm.where(Story.class).equalTo("id","id").findFirst();

story.deleteFromRealm();

Now, I want to pool the removed object and want to reuse it with different "id"(primary key) instead of creating a new object every single time.

The current implementation does not allow me to do this and throws an exception.

My question is, is there another way to achieve the same thing. If not, should this be a feature added to realm.

The requested code which throws the exception

Story story1 = StoryObjPool.getInstance().getStory();
            if(story1 != null){
                story1.setId(1234);
            }

The exception

java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.


at io.realm.BaseRealm.checkIfValid(BaseRealm.java:348)                                                                              
at io.realm.StoryRealmProxy.realmSet$id(StoryRealmProxy.java:177)                                                             
at com.hn.nishant.nvhn.model.Story.setId(Story.java:98)                                          
1
can you show the code about The current implementation does not allow me to do this and throws an exception - Linh
realm throws an illegal state exception saying the object has been closed as it is removed from database - Nishant Verma
I have another idea for solve your problem is you don't need delete object from Realm, just update this id - Linh
id is primary key. - Nishant Verma
If I fake your problem I will convert story to standalone object by use copyFromRealm(), then change the id and save it to realm by use copyToRealm() - Linh

1 Answers

2
votes
Story story = realm.where(Story.class).equalTo("id","id").findFirst();
// create standalone object that not reference to realm
Story stoyStandalone = realm.copyFromRealm(story);

story.deleteFromRealm();

// save standalone object to realm
stoyStandalone.setId(...);
realm.copyToRealm(stoyStandalone);