Cant add new object to RealmList due to null object reference

末鹿安然 提交于 2019-12-04 14:25:40

It is because you are trying to add a non-managed object to a managed list. This code here:

if (contactBook.getContacts().where().equalTo("name", name).findAll().size() == 0 && contactBook.getContacts().where().equalTo("number", number).findAll().size() == 0) {
    contactBook.getContacts().add(new Contact(name, number, false));
}

should be:

if (contactBook.getContacts().where().equalTo("name", name).findAll().size() == 0 && contactBook.getContacts().where().equalTo("number", number).findAll().size() == 0) {
    Contact newContact = realm.copyToRealm(new Contact(name, number, false));
    contactBook.getContacts().add(newContact);
}

Objects created with the new operator cannot be added to RealmLists that are already in the Realm without using one of the Realm.copyToRealmXXX methods, because it has to be converted to a proper (or managed) Realm object first. But the error message could definitely be better.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!