AndroidEnthusiast AndroidEnthusiast - 5 months ago 106
Android Question

Realm - Inner realm list object is not updated after copyToRealmOrUpdate()

I have a Realm object called Message (snippet below) which can also have nested messages of the same type in it:

public class Message extends RealmObject {

@PrimaryKey
private int id;

@Getter
@Setter
private RealmList<Message> nestedMessages;

}


At some point I need to update the list of nested messages e.g if a new nested message is added.

I'm doing that like this:

//newMessage is returned from a request

realm.beginTransaction();
RealmList<Message> nestedMessages = initialMessage.getNestedMessages();
nestedMessages.add(newMessage);
initialMessage.setNestedMessages(nestedMessages);
realm.copyToRealmOrUpdate(initialMessage);
realm.commitTransaction();

//Handle exceptions...


But after this the inner object "nestedMessages" is reset and the size is zero.

Is there something I'm missing here? Or does Realm works in a different way for this kind of use case?

NewMessage is the result of this response:

protected Response<Message> parseNetworkResponse(NetworkResponse response) {
if (isReqSuccessful(response)) {
try {
Gson gson = realmGson();
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, Message.class),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
return Response.error(new VolleyError());
}

Answer

Ehm no realm doesn't work this way. I don't really know how it interacts with lists but try the first solution, if it doesn't work the second one will definitely do:
1.

 realm.beginTransaction();
 RealmList<Message> nestedMessages = initialMessage.getNestedMessages();
 newMessage = realm.copyToRealmOrUpdate(newMessage);
 nestedMessages.add(newMessage); 
 realm.commitTransaction();

2.

RealmList<Message> nestedMessages = new RealmList<Message>();
RealmList<Message> oldMessages = initialMessage.getNestedMessages();
for(Message message: oldMessages){
    nestedMessages.add(message);
}
newMessage = realm.copyToRealmOrUpdate(newMessage);
nestedMessages.add(newMessage);
initialMessage.setNestedMessages(nestedMessages);
 realm.copyToRealmOrUpdate(initialMessage);
Comments