Realm-java: 'value' is not a valid managed object.

Created on 12 Jun 2018  路  5Comments  路  Source: realm/realm-java

Hello!
I have two RealmObject:

public class SongsDB extends RealmObject {
public String describe = "";
public boolean hasAccord = false;
public String lyrics = "";
public String lyricsAccord = "";
public String name = "";
public String bibleVerse = "";
public String bibleLink = "";
public SongsLanguageDB language;
public FavoriteDB favorite;
public AlbumsDB album;
@PrimaryKey
public String uuid = "";
}

AND

public class FavoriteDB extends RealmObject {
public SongsDB song;
}

When I have created SongsDB object in Realm and I try to update it, I have an error "'value' is not a valid managed object."

My code for the update:

Realm realm = Realm.getDefaultInstance();

    SongsDB songDB = realm.where(SongsDB.class).equalTo("uuid", "fdse-3424-vvf43").findFirst();

    FavoriteDB favoriteDB = new FavoriteDB();
    favoriteDB.song = songDB;

    realm.beginTransaction();
    songDB.favorite = favoriteDB; // WRITE HERE THE ERROR APPEARS
    realm.copyToRealm(favoriteDB);
    realm.commitTransaction();

Thanks for help!

O-Community T-Help

Most helpful comment

I think it's probably because.. the value is not a managed object, so it's not a valid managed object.

The following would work.

    realm.beginTransaction();
    songDB.favorite = realm.copyToRealm(favoriteDB);
    realm.commitTransaction();

All 5 comments

I think it's probably because.. the value is not a managed object, so it's not a valid managed object.

The following would work.

    realm.beginTransaction();
    songDB.favorite = realm.copyToRealm(favoriteDB);
    realm.commitTransaction();

Thanks it works!

It confuses me because when I add the songDB the first time to Realm I use the following and it works:

SongsDB songsDB = new SongsDB();

            songsDB.uuid = song.uuid;
            ...
            songsDB.hasAccord = song.hasAccord;

            if (favorites.contains(song.uuid)) {
                FavoriteDB favoriteDB = new FavoriteDB();
                favoriteDB.song = songsDB;
                songsDB.favorite = favoriteDB; // IN THIS LINE ERROR DOES'T APPEAR
            }

Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.copyToRealmOrUpdate(songsDB);
        realm.commitTransaction();

Could you please explain the difference between creating an object (songDB) and updating it?
Thanks

Well yeah, because in that example, songsDB is not a managed object, and it's saved "recursively" by copyToRealmOrUpdate

But if you use SongsDB songsDB = realm.createObject(SongsDB.class, uuid) (if object doesn't exist yet) then you won't have this discrepancy

I see, Thanks a lot!

I assume the above answered your question. If not, feel free to reopen

Was this page helpful?
0 / 5 - 0 ratings