天天看点

解决 Realm Only valid managed objects can be copied from Realm.

最近项目用到了ORM数据库Realm,功能强大,也非常方便,同时也带来了很多奇葩的问题

比如这个异常,找了半天也没有解决方案,经过千辛万苦终于找到了,这里做个记录,防止

以后再次入坑

先看代码

public RealmChatMessage getChatMessageSynchronous(String messageId) {
        RealmChatMessage realmChatMessage = null;
        try(Realm realm = Realm.getDefaultInstance()) {
            realmChatMessage = realm.where(RealmChatMessage.class)
                    .equalTo("messageId", messageId)
                    .findFirst();
        }
        return realmChatMessage;
    }

    public void sendMessage(String messageId, boolean playSound) {
        RealmChatMessage chatMessage = realmChatDao.getChatMessageSynchronous(messageId);
        if (chatMessage != null) {
            try(Realm realm = Realm.getDefaultInstance()) {
                RealmChatMessage unmanagedChatMessage = realm.copyFromRealm(chatMessage);
                sendMessage(unmanagedChatMessage, playSound);
            }
        } 
    }
           

表面上看没啥问题,但是一运行到15行就报标题的错,然后crash

原因是上一个方法传过来的chatMessage说是Invalid Object,真的是百思不得其解

最后发现Realm查询到一条数据的对象要再次使用Realm操作就要保证数据库不能关闭,

而getChatMessageSynchronous() 里面用了try(),()小括号中的对象会在try执行完毕

后自动释放掉,当然对象必须实现AutoCloseable接口,最终导致Realm数据库关闭

所以修改后的代码如下

public RealmChatMessage getChatMessageSynchronous(String messageId) {
        return Realm.getDefaultInstance().where(RealmChatMessage.class)
            .equalTo("messageId", messageId)
            .findFirst();
    }

    public void sendMessage(String messageId, boolean playSound) {
        RealmChatMessage chatMessage = realmChatDao.getChatMessageSynchronous(messageId);
        if (chatMessage != null) {
            try(Realm realm = Realm.getDefaultInstance()) {
                RealmChatMessage unmanagedChatMessage = realm.copyFromRealm(chatMessage);
                sendMessage(unmanagedChatMessage, playSound);
            }
        } 
    }
           

发现区别了吧,哈哈,现在又可以愉快的玩耍了

解决 Realm Only valid managed objects can be copied from Realm.