【问题标题】:How to set Default Values for fields in Realm?如何为领域中的字段设置默认值?
【发布时间】:2018-05-28 06:13:04
【问题描述】:

我们如何为领域模型字段设置默认值?

例子:

class Demo extends RealmObject{
    private String id; // I want to set this id to a uuid 
    private boolean isVisibile; // set this to default as true              
}

【问题讨论】:

    标签: java android sqlite mobile realm


    【解决方案1】:
    class Demo extends RealmObject{
        public Demo() {
            id = UUID.randomUUID().toString();
            isVisible = true;
        } 
    
        @PrimaryKey
        private String id; // I want to set this id to a uuid 
        private boolean isVisibile; // set this to default as true              
    }
    

    应该在 Realm 2.0+ 上工作

    【讨论】:

    • 在这种情况下我可以使用 realm.createObject(Demo.class, UUID.randomUuid().toString()) 吗?
    • 我认为是的,当然
    • @EpicPandaForce,如果领域找到相同的条目,领域.createObject(Demo.class, UUID.randomUuid().toString()) 会更新对象吗?如果不是,我该如何更新它?我正在使用 Gson 并获取 Mapped 对象,因此我需要在此映射后更新 Id。
    • 好吧,如果你得到一个具有相同随机 UUID 的新实例,那么我认为这被称为“超级倒霉”。但是不行,createObject如果类已经存在就会抛出异常,你可以先findFirst()看看它是否存在。
    猜你喜欢
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多