javaandroidrealmpojo

Alternative for maintaining separate constants for field names


While using Sqlite as DB in android, Many of us create a class like DbConstants where we save all the Table names, column names as constants.

In case of Realm DB, we prepare POJO classes which are represented as tables and fields as column names respectively.

Is there any way though which i can avoid creating another constants file here ?

Use Case :

POJO representing User table :

public class User extends RealmObject {

private String          name;
private int             age;

@Ignore
private int             sessionId;

// Standard getters & setters generated by your IDE…
public String getName() { return name; }
public void   setName(String name) { this.name = name; }
public int    getAge() { return age; }
public void   setAge(int age) { this.age = age; }
public int    getSessionId() { return sessionId; }
public void   setSessionId(int sessionId) { this.sessionId = sessionId;       
 }
}

so while we query User table as follows :

RealmResults<User> result = realm.where(User.class)
                              .equalTo("name", "John")
                              .or()
                              .equalTo("name", "Peter")
                              .findAll();

I don`t want to use the literals like “name” here. So any other elegant solution or best practice ?


Solution

  • The usual practice is having a static final constant in your model class like this:

    public class User extends RealmObject {
      public static final String NAME = "name";
      public static final String AGE = "age";
    
      // Fields, constructors, getters, setters,
    }
    
    realm.where(Person.class).equalTo(Person.NAME, "John").findAll();
    

    If you want an automated way of doing it you can take a look at: https://github.com/cmelchior/realmfieldnameshelper