Suresh Basnet Suresh Basnet - 1 year ago 259
Android Question

Is it necessary to extend every model class with RealmObject while working with realm?

I am using Realm ORM for my app. I have 3 model classes of which two extends RealmObject while the other one does not.

public class Party extends RealmObject implements Parcelable {
public int id;
public String name;
public String name_en;
public String name_ne;
public String address;
public String phoneNumber;
public String taxRegistrationNumber;
public String partyType;

the second class holds a field of type Party. But this does not extends RealmObject

public class CreatePurchaseOrder implements Parcelable {
public int voucherNumber;
public Date date;
public Party party;
String agent;

The third class holds a field for CreatePurchaseOrder and extends RealmObject

[public class CreatePurchaseOrderRow extends RealmObject implements Parcelable {
public int id;
private int serialNumber;
private String specification;
private float quantity;
private float rate;
private String remarks;
private boolean fulfilled;
private CreatePurchaseOrder createPurchaseOrder;

With this approach it generates an error message
screenshot of error message

screenshot of error message

So is it necessary to extend every Model class with RealmObject?

Answer Source

Technically you don't have to extend RealmObject directly from your model class.

The docs say:

Realm model classes are created by extending the RealmObject base class.

Which implies that if you don't extend RealmObject, your class is not a Realm model, thus it can't be stored in a realm.

However you can also implement the RealmModel interface and annotate your model class with @RealmClass

public class MyModel implements RealmModel {


as mentioned here:

Why do model classes need to extend RealmObject?

We need to add Realm specific functionality to your model classes. It also allows us to use generics in our APIs, making it easier to read and use. If you don’t want to extend a base class you can instead implement the RealmModel interface.

and here:

An alternative to extending the RealmObject base class is implementing the RealmModel interface and adding the @RealmClass annotation.

It is a different means to achieve the same goal. The issue you experience is the same though. You cannot store plain objects in a realm. You must hook up your model class to Realm using one of two ways mentioned above.

Do note that if you use the 2nd approach, the usage is different:

// With RealmObject

// With RealmModel
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download