Creating RealmList of Primitive Datatype(String) in Realm Version<4.0.0

Sometime in December 2021, I was handed a ticket to work on before the break, but it appeared Christmas came early as I had a present waiting for me. So, when I jumped on Android Studio to get my task started and finished before applying for *PTO, I hit a wall soon before I could even build.

So what happened?

The task required me to interact with Realm, an object database by MongoDb that is used to store data in users' devices locally. It was my first time working with Realm as I’ve always used Room for local storage but that wasn’t the challenge as Realm has great documentation.

Want some juxtaposition between Realm and Room, check here, here and here.

My challenge was wrapped around creating RealmList of String type. Surprising at first, to be honest as I expected it to support primitive datatypes. But hold on, what’s a RealmList? RealmList is used to model one-to-many relationships in a RealmObject, you can read more about it here.

So here’s the gist, Realm didn’t support RealmList for primitive datatypes until version 4.0.0. The project’s realm version was less so I had two options, upgrade its version in Gradle or find a way around it.

Of course, I chose the easy route of upgrading the version to 4.0.0, and yes I fixed my issue, but damn I broke a lot more things. Time to eat humble pie and do some more research. Going through the ChangeLog.MD, and with the help of a senior colleague, the necessary changes were made to ensure the whole project was built successfully but there remained challenges.

So back to the elephant in the room.

Since Realm didn’t support RealmList for String type in versions less than 4.0.0, the way around that would be to wrap String in a RealmObject.

For example, if you wanted to retrieve a RealmList of picture links which is a String type, create a class:

public class CertificatePictureLink extends RealmObject {
    //property
    public String value;
}

In your RealmObject model class:

public class UserData extends RealmObject {
    @SerializedName(“id”)
    Private String id;

    @SerializedName(“certificatePictureLinks”)
    Private RealmList<CertificatePictureLink> certificatePictureLinks;

//getters and setterspublic List<CertificatePictureLink> getCertificatePicturesLink() { return certificatePictureLinks;}
}

And then in your network class, you can retrieve your list of strings in onResponse after determining if the call is successful. Voila.

Have challenges with Gson deserialization? Check out this StackOverflow conversation.

*PTO: Paid Time Off