Search code examples
androidrealm

Custom constructor error with Realm model class


Realm throws the following error message if you have a custom constructor within the Realm model class.

Class <class name> must declare a public constructor with no arguments if it contains custom constructors

Below is the Realm model class.

@RealmClass
public class User implements RealmModel {

public User(Integer id, String email) {
    this.id = id;
    this.email = email;
}

How do you get rid of it?


Solution

  • Realm requires every Realm model class to have a public constructor with no arguments. This is because of the method createObject(Class<E> clazz). For example, to get the User class to work, it'd look like the following.

    @RealmClass
    public class User implements RealmModel {
    
    public User() {
    
    }
    
    public User(Integer id, String email) {
        this.id = id;
        this.email = email;
    }